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<>();
Related
This question already has answers here:
Initialization of an ArrayList in one line
(34 answers)
Closed 5 years ago.
I have a DataHandaling class that is used to do the logic, it is also suppose to be an easier way to retrieve an ArrayList from multiple activities, But when I start a new activity the ArrayList is null
(NOTE: The array is not empty because I have used the same array multiple times in the main activity, this problem is only a case when I start a new activity)
The code from DataHandaling
public class DataHandaling {
EnviroClass enviroClass = new EnviroClass();
private ArrayList<Event> eventArray = new ArrayList<Event>();
public ArrayList<Event> getEventArray() {
return eventArray;
}
public void getEvents() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(enviroClass.url() + "/api/events/" + 7)
.build();
client.newCall(request)
.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
JSONObject eventObject = new JSONObject(response.body().string());
JSONArray eventJsonArray = eventObject.getJSONArray("events");
for (int i = 0; i<eventJsonArray.length(); i++) {
eventObject = eventJsonArray.getJSONObject(i);
eventObject = eventObject.getJSONObject("event");
eventArray.add(new Event(eventObject.getString("name"), eventObject.getString("address"), eventObject.getString("image"), "100" ,eventObject.getString("start_date"), eventObject.getString("end_date"), eventObject.getInt("id")));
}
EventListAdapter adapter = new EventListAdapter(null, null);
adapter.swap(eventArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
This is where it is breaking in the new activity
textView.setText(dh.getEventArray().get(0).getName());
The interaction listener to open the new activity
#Override
public void onListFragmentInteraction(int id) {
Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
intent.putExtra("id", id);
MainActivity.this.startActivity(intent);
}
The activity where it is breaking
public class ProfileActivity extends AppCompatActivity {
DataHandaling dh = new DataHandaling();
int eventArrayId;
TextView eventDescription;
TextView eventName;
ImageView eventImage;
ArrayList<Event> eventArray = new ArrayList<Event>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
getSupportActionBar().setHomeButtonEnabled(true);
Intent intent = getIntent();
eventArrayId = intent.getIntExtra("id", 0);
eventName = (TextView) findViewById(R.id.eventNameTextView);
eventName.setText(dh.getEventArray().get(0).getName());
}
}
Stack Trace:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.gb.socilizer_app/com.app.gb.socilizer.Activities.ProfileActivity}: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:411)
at com.app.garethbecker.socializer.Activities.ProfileActivity.onCreate(ProfileActivity.java:39)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
You are creating new object of DataHandling in the activity. So it will not be the same object that you had previously used and which has data in it.
First :- If your ArrayList<Event> is empty and if you get 0th index element then you'll get NullPointerException while Executing this line :- dh.getEventArray().get(0).getName() so it is replaced by null.getName() which will break.
So if you want to get index basis Element form collection firsat checkl whether the Collection is empty or not.
Like this:-
//if the ArrayList is not Empty then only iterate over it.
if(!dh.getEventArray().isEmpty())
{
textView.setText(dh.getEventArray().get(0).getName());
}
Second:- Check the logic for adding the Event In ArrayList<Event>.
Your method is called getArray(), yet you're invoking getEventArray(). Maybe it is the reason.
EDIT: Now that your message is edit we have something to work on.
DataHandaling dh = new DataHandaling();
This is a new DataHandaling object, and never in your code you're updating him. So I guess that its ArrayList is empty by default.
I'm getting a FATAL EXCEPTION: main when I run the app. It run first but for a few seconds it crash.
Here is my Logcat :
java.lang.RuntimeException: Could not read input channel file descriptors from parcel.
at android.view.InputChannel.nativeReadFromParcel(Native Method)
at android.view.InputChannel.readFromParcel(InputChannel.java:148)
at android.view.IWindowSession$Stub$Proxy.addToDisplay(IWindowSession.java:752)
at android.view.ViewRootImpl.setView(ViewRootImpl.java:527)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:282)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.Dialog.show(Dialog.java:298)
at android.app.AlertDialog$Builder.show(AlertDialog.java:993)
at com.mobext.shakeys.ActivityMain$ProcessData.onPostExecute(ActivityMain.java:545)
at com.mobext.shakeys.ActivityMain$ProcessData.onPostExecute(ActivityMain.java:212)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Inside my ActivityMain.java:542 in alrt.show() this is where the logcat point it:
#Override
protected void onPostExecute(Boolean result) {
Log.i(TAG, "onPostExecute");
super.onPostExecute(result);
if(result){
Log.i(TAG, "TASK IS DONE");
try {
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
app.saveToLastPref(ActivityMain.this, app.PREFS_PREV_VERSION, pInfo.versionName);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent = new Intent(getApplicationContext(), ActivityMenuPage.class);
startActivity(intent);
finish();
}else{
ActivityMain.this.deleteDatabase("DBSHAKEYS");
Builder alrt = new AlertDialog.Builder(mcontext);
alrt.setMessage("Update failed. Please check your internet connection and try again.");
alrt.setPositiveButton("Okay", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alrt.show();
}
}
}
And in ActivityMain.java:212 :
public class ProcessData extends AsyncTask<Void, Void, Boolean>
I think Builder is your custom class that you are using now to show the AlertDialog.
Here is what may happened
The onPostExecute() method was called automatically after your some background process was finished executing. And then It tried to use the Builder class which may be currently being used by another process and still running in the memory.
How can it be solved then ?
Review your code and see if the dialog is already being shown using
Builder class.
Simply change this line
Builder alrt = new AlertDialog.Builder(mcontext); to normally AlertDialog.Builder alrt = new AlertDialog.Builder(mcontext);
and see if this works.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm currently working on an android app to fetch data from the server. It crashes and I get a NullPointerException. Can anyone help me edit my code/ list out my error?
Here is my code (I have read a through few of the forums but did not really understand how to solve my problem)
public class MainActivity extends AppCompatActivity {
ListView lvPost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvPost = (ListView)findViewById(R.id.lvPost);
String url2 = "http://192.168.0.146/client/login.php?format=json";
PostResponseAsyncTask task2 = new PostResponseAsyncTask(MainActivity.this, new AsyncResponse() {
#Override
public void processFinish(String s) {
ArrayList<Post> postList =
new JsonConverter<Post>().toArrayList(s, Post.class);
ArrayList<String> titles = new ArrayList<String>();
for (Post value:postList) {
titles.add(value.post_title);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, titles);
lvPost.setAdapter(adapter);
}
});
task2.execute(url2);
}
}
Here is my logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Iterator java.util.ArrayList.iterator()' on a null object reference
at com.example.1231.t12.MainActivity$1.processFinish(MainActivity.java:40)
at com.kosalgeek.genasync12.PostResponseAsyncTask.onPostExecute(PostResponseAsyncTask.java:188)
at com.kosalgeek.genasync12.PostResponseAsyncTask.onPostExecute(PostResponseAsyncTask.java:27)
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:145)
at android.app.ActivityThread.main(ActivityThread.java:6075)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
It looks like String s parameter is null, use logging to confirm. In such case Gson.fromJson() returns null as a result. Then you're trying to iterate through the list postList which is null and this results to NullPointerException.
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 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());