I am trying to build an app with master and detail layout using fragments and data is coming from from parsing JSOnArray by consuming webservice using Asynctask.
No matter what fixes I apply as suggested for similar issues over various forums, I always see this error from logcat:
FATAL EXCEPTION: main
Process: com.example.masterdetail, PID: 26639
java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.d(Log.java:139)
at com.example.masterdetail.ItemsListFragment.populateResult(ItemsListFragment.java:108) //this is the line where I am building an arraylist in ItemsListFragment.java
at com.example.masterdetail.AsyncRequest.onPostExecute(AsyncRequest.java:147)
at com.example.masterdetail.AsyncRequest.onPostExecute(AsyncRequest.java:23)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
==================
ItemsListFragment.java:
public void populateResult(String response) {
/*TextView resultView = (TextView)getActivity().findViewById(R.id.textUrlContent);
resultView.setText(response);*/
try {
ListView lvItems = (ListView) getActivity().findViewById(R.id.lvItems);
ArrayList<Item> products = new ArrayList<Item>();
JSONObject jsonObject = new JSONObject(response);
JSONObject responseObj = jsonObject.getJSONObject("response");
JSONArray jsonDataProducts = responseObj.getJSONArray("products");
for (int i = 0; i < jsonDataProducts.length(); i++) {
JSONObject oneObject = jsonDataProducts.getJSONObject(i);
Item dataProduct = new Item();
dataProduct.setTitle(oneObject.getString("title"));
dataProduct.setBody(oneObject.getString("id"));
products.add(dataProduct); //***Line: 108 from above error msg ************
}
adapterItems = new ArrayAdapter<Item>(getActivity(),
android.R.layout.simple_list_item_activated_1, products);
lvItems.setAdapter(adapterItems);
lvItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View item, int position,
long rowId) {
// Retrieve item based on position
Item i = adapterItems.getItem(position);
// Fire selected event for item
listener.onItemSelected(i);
}
});
} catch (Exception e) {
Log.d("ReadRdaJSONFeedTask", e.getLocalizedMessage());
}
}
Log.d("ReadRdaJSONFeedTask", e.getLocalizedMessage());,
The e.getlocalizedMessage() is returning null. Check before calling.
Log.d("ReadRdaJSONFeedTask", e.getLocalizedMessage() == null ? "" : e.getLocalizedMessage());
Related
I have a MultiAutoCompleteTextView where data is taken from Firestore. When i set the data in ArrayAdapter, i get an error like below. I followed the following method https://stackoverflow.com/a/2965808/2123594 , but I'm still confused where i should put Arrays.asList to my code.
Error :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.learn.count, PID: 21871
java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:404)
at java.util.AbstractList.add(AbstractList.java:425)
at android.widget.ArrayAdapter.add(ArrayAdapter.java:179)
at com.learn.count.addproducts.AddItems$4.onComplete(AddItems.java:147)
at com.google.android.gms.tasks.zzj.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
MultiAutoCompleteTextView Code :
String[] arrayUoM = new String[]{null};
ArrayAdapter<String> adapterUoM = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arrayUoM);
// Check if document is available
collectionUoM.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot documentSnapshot : task.getResult()) {
if (task.getResult().isEmpty()) {
Log.e("TAG", "UoM not available");
} else {
String getName = documentSnapshot.getString("uoMName");
adapterUoM.add(getName);
}
}
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AddItems.this, "Error : " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
MultiCompleteUoM.setAdapter(adapterUoM);
MultiCompleteUoM.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
Actually there are multiple problems in your code.
Problem - 1: You have initialized your ArrayAdapter with array of null, which cause NullPointerExceptio.
Problem - 2: You have used array of String String[] to create ArrayAdapter. The ArrayAdapter, on being initialized by an array, converts the array into a AbstractList (List) which cannot be modified. Hence it cause UnsupportedOperationException, when you try to add item to ArrayAdapter.
Solution: To resolve both of the problem, You have to use ArrayList instead of array.
ArrayList<String> arrayUoM = new ArrayList<>();
Can someone help me?
I don't know why have I javaNullExepction in LayoutInflater.Here is my code :
This code is in fragment :
ServiceManager.getInstance().getCampaign( new Callback <Campaign>() {
#Override
public void success(Campaign campaign, Response response) {
campaigns = campaign;
adapter = new RecyclerCampaignAdapter(getActivity(), campaign);
recyclerView.setAdapter(adapter);
recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).marginProvider(adapter).showLastDivider().build());
adapter.notifyDataSetChanged();
if (progressBar.isShown()) {
progressBar.setVisibility(View.INVISIBLE);
}
}
#Override
public void failure(RetrofitError retrofitError) {
Toast.makeText(getActivity(), "Failed" + retrofitError, Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
here is code in my adapter :
public RecyclerCampaignAdapter (Activity activity, Campaign campaignList) {
this.activity = activity;
this.campaignList = campaignList;
this.inflater= LayoutInflater.from(activity);
}
I think getActivity() == null I don't know how can I fix it.
java.lang.NullPointerException
at android.view.LayoutInflater.from(LayoutInflater.java:212)
at tr.org.yyd.yeryuzudoktorlari.adapter.RecyclerCampaignAdapter.(RecyclerCampaignAdapter.java:38)
at tr.org.yyd.yeryuzudoktorlari.fragment.CampaignFragment$1.success(CampaignFragment.java:69)
at tr.org.yyd.yeryuzudoktorlari.fragment.CampaignFragment$1.success(CampaignFragment.java:65)
at retrofit.CallbackRunnable$1.run(CallbackRunnable.java:45)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5756)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
EDIT:
I use replace method on frgment transaction when user clicks on an item from menu.So CampaignFragment works okey when the user clicks in first time but it crashes when user clicks again while it is still on.
If I change into another fragment and come back to CampaginFragment there is no crash.
The answer just that.I don't know how that fix it but it worked.It's just a control.
if (getActivity() != null) {
adapter = ....
I’m having a navigation drawer for my app that contains a menu with which I can navigate between the fragments. The first fragment that i get after the app lunch is the Home which contains a listView and a footer attached in the bottom (is just for the test). The problem is when I lunch the Home fragment for the first time nothing happen and its work very well, but when I change the fragments from the navigation drawer and trying to get back the home fragment the app crash. The error log show me a null pointer Exception. Thes is my code detail
onCreateView method
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (v != null) {
ViewGroup parent = (ViewGroup) v.getParent();
if (parent != null)
parent.removeView(v);
}
try {
v = inflater.inflate(R.layout.fragment_homes, container, false);
listView = (ListView) v.findViewById(R.id.homeList);
l = new HomeListAdapter(this, homeList);
if(l == null)
Log.i("tag","null");
listView.setAdapter(l);
} catch (InflateException e) {
}
return v;
}
onPostExecute method
#Override
protected void onPostExecute(final String res) {
/*try {
jObj = new JSONArray(res);
} catch (JSONException e) {
e.printStackTrace();
}*/
/* JSONArray j = null;
try {
j = new JSONArray(res);
} catch (JSONException e) {
e.printStackTrace();
}*/
// Parsing json
for (int i = 0; i < 5; i++) {
//JSONObject obj = j.getJSONObject(i);
Home home = new Home();
//String photoNews = java.net.URLDecoder.decode(obj.getString("photonews"), "UTF-8");
home.setNomC("Karim Ennassiri");
home.setPhotoP("http://i1239.photobucket.com/albums/ff509/FestusMANAFEST/iker-casillas20Wallpaper__yvt2.jpg");
home.setPhotoAr("http://voyage-essaouira-maroc.com/upload/apostrophe_image_(13).jpg");
home.setText("Chlada V2.0 Edition");
home.setNbrSick("5");
home.setNbrComm("8");
home.setNbrShare("0");
homeList.add(home);
}
l.notifyDataSetChanged();
//pDialog.hide();
}
The error log
10-10 09:31:30.884 2447-2447/com.example.user.unchained E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.user.unchained, PID: 2447
java.lang.NullPointerException
at com.example.user.unchained.HomesActivity$PlaceholderFragment$FeedsTask.onPostExecute(HomesActivity.java:375)
at com.example.user.unchained.HomesActivity$PlaceholderFragment$FeedsTask.onPostExecute(HomesActivity.java:277)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
And this is exactly the line that cause the error : l.notifyDataSetChanged();. I notice that the error is just in the case when i'm trying to display the fragment for the secode time.
So any help please ? Thanks !
You need to use this in doInBackground.
#Override
protected Void doInBackground(void... ) {
try {
for (int i = 0; i < 5; i++) {
//JSONObject obj = j.getJSONObject(i);
Home home = new Home();
//String photoNews = java.net.URLDecoder.decode(obj.getString("photonews"), "UTF-8");
home.setNomC("Karim Ennassiri");
home.setPhotoP("http://i1239.photobucket.com/albums/ff509/FestusMANAFEST/iker-casillas20Wallpaper__yvt2.jpg");
home.setPhotoAr("http://voyage-essaouira-maroc.com/upload/apostrophe_image_(13).jpg");
home.setText("Chlada V2.0 Edition"); //give some other name in getter setter for setText in Home.java. It makes not to understand whether you are using setText for textview assigning.
home.setNbrSick("5");
home.setNbrComm("8");
home.setNbrShare("0");
homeList.add(home);
}
postExecute is used to display UI. don't perform heavy operation like parsing in PostExecute.
I am currently creating a Android GoogleMaps app and have stored a list of Locations on a database on an online server. I'm pulling them through successfully and now I want to use the Actionbar searchview to create a listview that the user can search and it will change the currently loaded data to only show the ones linked to the currently selected Location.
However I am coming across the error of cannot be cast to android.content.Context when trying to put the arraylist into the adapter after changing the ListViewAdapter code to be a runnable due to where I am calling it. My main activity code is as follows:
TownSelector ts;
ListView townList;
ListViewAdapter townAdapter; <---set variable for adapter here
String[] townID;
String[] townName;
ArrayList<TownSelector> arraylist = new ArrayList<TownSelector>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setContentView(R.layout.search);
setUpMapIfNeeded();
// Hashmap for ListView
locationList = new ArrayList<HashMap<String, String>>();
// Locate the ListView in listview_main.xml
townList = (ListView) findViewById(R.id.listview);
}
class LoadAllInfo extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> paramsLocations = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject jsonLocations = jParser.makeHttpRequest(url_all_locations, "GET", paramsLocations);
//Get all offer
if(jsonLocations != null)
{
// Check your log cat for JSON reponse
Log.d("All Locations: ", jsonLocations.toString());
try {
// Checking for SUCCESS TAG
int success = jsonLocations.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Offers
locations = jsonLocations.getJSONArray(TAG_LOCATIONS);
// looping through All Offers
for (int i = 0; i < locations.length(); i++) {
JSONObject c = locations.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_LID);
String locationName = c.getString(TAG_LNAME);
// creating new HashMap
HashMap<String, String> locationsListMap = new HashMap<String, String>();
// adding each child node to HashMap key => value
locationsListMap.put(TAG_LID, id);
locationsListMap.put(TAG_LNAME, locationName);
// adding HashList to ArrayList
locationList.add(locationsListMap);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into map marker
* */
//TODO setMapMarkers
townID = new String[locationList.size()];
townName = new String[locationList.size()];
for(int l = 0; l <= (locationList.size() - 1); l++)
{
Log.d("Hello", "location loop");
Log.d("Hello", locationList.get(l).toString().split("Location_ID=")[1].split(",")[0]);
townID[l] = locationList.get(l).toString().split("Location_ID=")[1].split(",")[0];
Log.d("Hello", locationList.get(l).toString().split("Location_Name=")[1].split(",")[0].replace("}",""));
townName[l] = locationList.get(l).toString().split("Location_Name=")[1].split(",")[0].replace("}","");
}
for (int i = 0; i < townID.length; i++)
{
ts = new TownSelector(townID[i], townName[i]);
// Binds all strings into an array
arraylist.add(ts);
}
// Pass results to ListViewAdapter Class
townAdapter = new ListViewAdapter(this, arraylist); <--Create new instant of adapter here
// Binds the Adapter to the ListView
townList.setAdapter(townAdapter); //This is the line that causes a crash
}
});
}
}
ListViewAdapter code:
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<TownSelector> locationlist = null;
private ArrayList<TownSelector> arraylist;
public ListViewAdapter(Runnable runnable, List<TownSelector> locationlist) {
mContext = (Context) runnable;
this.locationlist = locationlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<TownSelector>();
this.arraylist.addAll(locationlist);
}
I changed the ListViewAdapter code to the what is below after finding this stackflow question android callback fails in fragment fails cannot be cast to android.content.Context
public ListViewAdapter(Context context,Runnable runnable, List<TownSelector> locationlist) {
mContext = context;
this.runnable = runnable;
this.locationlist = locationlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<TownSelector>();
this.arraylist.addAll(locationlist);
}
error callstack:
09-22 03:58:03.467: E/AndroidRuntime(15586): FATAL EXCEPTION: main
09-22 03:58:03.467: E/AndroidRuntime(15586): Process: biz.nickbullcomputing.bevnav, PID: 15586
09-22 03:58:03.467: E/AndroidRuntime(15586): java.lang.ClassCastException: biz.nickbullcomputing.bevnav.MainActivity$LoadAllInfo$1 cannot be cast to android.content.Context
09-22 03:58:03.467: E/AndroidRuntime(15586): at biz.nickbullcomputing.bevnav.ListViewAdapter.<init>(ListViewAdapter.java:25)
09-22 03:58:03.467: E/AndroidRuntime(15586): at biz.nickbullcomputing.bevnav.MainActivity$LoadAllInfo$1.run(MainActivity.java:409)
09-22 03:58:03.467: E/AndroidRuntime(15586): at android.app.Activity.runOnUiThread(Activity.java:4794)
09-22 03:58:03.467: E/AndroidRuntime(15586): at biz.nickbullcomputing.bevnav.MainActivity$LoadAllInfo.onPostExecute(MainActivity.java:376)
09-22 03:58:03.467: E/AndroidRuntime(15586): at biz.nickbullcomputing.bevnav.MainActivity$LoadAllInfo.onPostExecute(MainActivity.java:1)
09-22 03:58:03.467: E/AndroidRuntime(15586): at android.os.AsyncTask.finish(AsyncTask.java:632)
09-22 03:58:03.467: E/AndroidRuntime(15586): at android.os.AsyncTask.access$600(AsyncTask.java:177)
09-22 03:58:03.467: E/AndroidRuntime(15586): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
09-22 03:58:03.467: E/AndroidRuntime(15586): at android.os.Handler.dispatchMessage(Handler.java:102)
09-22 03:58:03.467: E/AndroidRuntime(15586): at android.os.Looper.loop(Looper.java:157)
09-22 03:58:03.467: E/AndroidRuntime(15586): at android.app.ActivityThread.main(ActivityThread.java:5867)
09-22 03:58:03.467: E/AndroidRuntime(15586): at java.lang.reflect.Method.invokeNative(Native Method)
09-22 03:58:03.467: E/AndroidRuntime(15586): at java.lang.reflect.Method.invoke(Method.java:515)
09-22 03:58:03.467: E/AndroidRuntime(15586): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
09-22 03:58:03.467: E/AndroidRuntime(15586): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
09-22 03:58:03.467: E/AndroidRuntime(15586): at dalvik.system.NativeStart.main(Native Method)
this part in your asyncTask townAdapter = new ListViewAdapter(this, arraylist); is not correct. your editor should have shown error. you need to pass YourActivityName.this just this is sending LoadAllInfo as context which is wrong
I'm trying to retrieve data from a json with multiple values and cast it into a listview but im gettting the error java.util.hashmap cannot be cast to java.util.list.
I'm using volley.
The FeedListActivity Class:
public void updateList() {
feedListView= (ListView) findViewById(R.id.custom_list);
feedListView.setVisibility(View.VISIBLE);
progressbar.setVisibility(View.GONE);
feedListView.setAdapter(new CustomListAdapter(this, feedList));
feedListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = feedListView.getItemAtPosition(position);
ClientesContatosModel newsData = (ClientesContatosModel) o;
Intent intent = new Intent(FeedListActivity.this, FeedDetailsActivity.class);
intent.putExtra("nome", newsData);
startActivity(intent);
}
});
}
JSONArray dados = json.getJSONArray("dados");
// parsing json object
for (int i = 0; i < dados.length(); i++) {
JSONObject item = dados.getJSONObject(i);
feedList = new ArrayList<ClientesModel>();
ClientesModel mClientesModel = new ClientesModel();
ClientesContatosModel mClientesContatoModel = new ClientesContatosModel();
/* cadastra os dados necessários no objeto no modelo */
mClientesModel.setId(item.optInt("id"));
mClientesModel.setNome(item.optString("nome"));
mClientesModel.setTipo_pessoa(item.optString("tipo_pessoa"));
mClientesModel.setInformacoes_adicionais(item.optString("informacoes_adicionais"));
mClientesModel.setCpf(item.optString("cpf"));
mClientesModel.setCnpj(item.optString("cnpj"));
JSONArray contatos = item.getJSONArray("contatos");
for (int j = 0; j < contatos.length(); j++) {
JSONObject data = contatos.getJSONObject(j);
mClientesContatoModel.setNome(data.optString("nome"));
mClientesContatoModel.setCargo(data.optString("cargo"));
FeedDetailsActivity class:
public class FeedDetailsActivity extends Activity {
private ClientesContatosModel feed;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed_details);
feed = (ClientesContatosModel) this.getIntent().getSerializableExtra("nome");
if (null != feed) {
TextView title = (TextView) findViewById(R.id.title);
title.setText(feed.getNome());
}
}
Here is the Log:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.javatechig.feedreader/com.javatechig.feedreader.FeedDetailsActivity}: java.lang.ClassCastException: java.util.HashMap cannot be cast to com.javatechig.feedreader.model.ClientesContatosModel
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: java.util.HashMap cannot be cast to com.javatechig.feedreader.model.ClientesContatosModel
at com.javatechig.feedreader.FeedDetailsActivity.onCreate(FeedDetailsActivity.java:26)
at android.app.Activity.performCreate(Activity.java:5248)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
Because HashMap#values() return a java.util.Collection and you cant cast Collection into ArrayList, thus you get ClassCastException.
where as in case of ArrayList(HashMap.values()) ArrayList constructor takes Collection as an argument. Thus you wont get ClassCastException when you pass HashMap.values() as an argument to ArrayList.
HashMap#values(): check the return type in the source, as ask yourself, can a java.util.Collection be casted into java.util.ArrayList ?? No
public Collection<V> values() {
921 Collection<V> vs = values;
922 return (vs != null ? vs : (values = new Values()));
923 }
ArrayList(Collection): check the argument type in the source. can a method whose argument is a super type accepts sub type ? Yes
public ArrayList(Collection<? extends E> c) {
151 elementData = c.toArray();
152 size = elementData.length;
153 // c.toArray might (incorrectly) not return Object[] (see 6260652)
154 if (elementData.getClass() != Object[].class)
155 elementData = Arrays.copyOf(elementData, size, Object[].class);
156 }