App crashed when arrayAdapter.notifyDataSetChanged() was called - java

public class Activity_search extends ActionBarActivity {
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mArrayAdapter;
private ArrayList<String> mArrayList;
private boolean isDiscovering;
private AdapterView.OnItemClickListener mClickListener = new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> adapterView,View view,int position, long id ){
mBtAdapter.cancelDiscovery();
isDiscovering=false;
Toast.makeText(getApplicationContext(),"Selected",Toast.LENGTH_SHORT).show();
String tmp1 = ((TextView)view).getText().toString();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_search);
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
mArrayList = new ArrayList<String>();
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(this,R.layout.listview_row,mArrayList);
ListView listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(mArrayAdapter);
listView.setOnItemClickListener(mClickListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_activity_search, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String tmp=device.getName() + "\n" + device.getAddress();
Context appContext = getApplicationContext();
Toast.makeText(appContext,tmp,Toast.LENGTH_LONG).show();
mArrayList.add(tmp);
mArrayAdapter.notifyDataSetChanged();
}
if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
Toast.makeText(getApplicationContext(),"Discovery Finished",Toast.LENGTH_SHORT).show();
}
}
};
public void onBtn2Clicked(View view) {
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
Context appContext = getApplicationContext();
if(!isDiscovering) {
mBtAdapter.startDiscovery();
Toast.makeText(appContext, "Discovery Started", Toast.LENGTH_SHORT).show();
isDiscovering=true;
} else {
mBtAdapter.cancelDiscovery();
Toast.makeText(appContext,"Discovery Canceled",Toast.LENGTH_SHORT).show();
isDiscovering=false;
}
}
public void onDestroy(){
super.onDestroy();
if(mBtAdapter.isDiscovering()){
mBtAdapter.cancelDiscovery();
}
unregisterReceiver(mReceiver);
}
}
App always crashed when it called the function as mentioned at above, And its error code is
02-13 16:04:47.974 27328-27328/com.skyjohn.nxtrpc E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.bluetooth.device.action.FOUND flg=0x10 (has extras) } in com.skyjohn.nxtrpc.Activity_search$2#41532570
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:798)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.skyjohn.nxtrpc.Activity_search$2.onReceive(Activity_search.java:90)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:788)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
But if i hardcoded mArrayList.add("abc") into the code, the "abc" will appear, but if I do it dynamicly (when I received a new bluetooth device) , the app crashed.

Caused by: java.lang.NullPointerException
at com.skyjohn.nxtrpc.Activity_search$2.onReceive
mArrayAdapter is null because creating new object of Adapter in onCreate method with same name which declare as class level.
To fix error use:
mArrayAdapter = new ArrayAdapter<String>(this,R.layout.listview_row,mArrayList);
in onCreate method instead of creating new object of ArrayAdapter.

inside onCreate you are hiding the scope of the class member variable mAdapter, declaring and initialazing it in the local scope of onCreate. The fix is to remove ArrayAdapter<String> from onCreate, leaving only
mArrayAdapter = new ArrayAdapter<String>(this,R.layout.listview_row,mArrayList);

Related

Android: Fragment is not attached to Activity error

So I'm working on an app and I had this part working for days, and out of no where it just stopped working for no reason...
I also had the same error when I was trying to use another headless fragment in my MainActivity, but ended up replacing the fragment with inner methods inside of the MainActivity and everything went back to working properly.
However, I can't rewrite every bit of code I have just to avoid using fragments. The fragment code is below.
public class IMEIFragment extends Fragment implements ActivityCompat.OnRequestPermissionsResultCallback{
public static final String TAG_IMEI = "IMEILoader";
protected Activity mActivity;
private String RecordedIMEI;
//public static final String CHECK_INTERNET = "network_connection";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return null; //Do we need this at all?
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Activity activity = context instanceof Activity ? (Activity) context : null;
mActivity = activity;
}
//Is this needed?
#SuppressWarnings("deprecation")
#Override
public void onAttach(Activity activity) {
activity = getActivity();
if (isAdded() && activity != null) {
super.onAttach(activity);
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
mActivity = activity;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public void onDetach() {
super.onDetach();
mActivity = null;
}
public String loadIMEI(Context context) {
if (Build.VERSION.SDK_INT >= 23) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
// READ_PHONE_STATE permission has not been granted.
requestPermissions(context);
} else {
// READ_PHONE_STATE permission is already been granted.
RecordedIMEI = permissionGrantedActions(context);
}
if (RecordedIMEI != null) {
Log.i("loadIMEIService", "IMEI number returned!");
}
} else {
// READ_PHONE_STATE permission is already been granted.
RecordedIMEI = permissionGrantedActions(context);
}
if (RecordedIMEI != null) {
Log.i("loadIMEIService", "IMEI number returned!");
}
return RecordedIMEI;
}
private void requestPermissions(Context context) {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
Log.i("loadIMEIService", "READ_PHONE_STATE permission not granted, asking for it...");
// TODO create proper notification content
PermissionHelper.requestPermissions(((PriceActivity) getActivity()),
new String[]{Manifest.permission.READ_PHONE_STATE},
Constants.PERM_REQUEST_PHONE_STATE,
getString(R.string.notify_perm_title),
getString(R.string.notify_perm_body),
R.drawable.ic_security);
}
}
// Callback received when a permissions request has been completed.
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
boolean isGranted = false;
for (int i = 0; i < grantResults.length; i++)
if (permissions[i].equals(Manifest.permission.READ_PHONE_STATE) && (grantResults[i] == PackageManager.PERMISSION_GRANTED))
isGranted = true;
if (isGranted) {
Context context = getActivity().getApplicationContext();
permissionGrantedActions(context);
}
else
Log.w("loadIMEIService", "READ_PHONE_STATE permission not granted. loadIMEI will not be available.");
}
public String permissionGrantedActions(Context context) {
//Have an object of TelephonyManager
TelephonyManager tm =(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
//Get IMEI Number of Phone
String IMEINumber = tm.getDeviceId();
if(IMEINumber != null) {
Log.i("loadIMEIService", "IMEI number recorded!");
}
return IMEINumber;
}
}
Error is below:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.project1, PID: 5498
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.project1/com.android.project1.main.MainActivity}: java.lang.IllegalStateException: Fragment IMEIFragment{3e80da7 IMEILoader} not attached to Activity
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalStateException: Fragment IMEIFragment{3e80da7 IMEILoader} not attached to Activity
at android.app.Fragment.getResources(Fragment.java:805)
at android.app.Fragment.getString(Fragment.java:827)
at com.android.project1.fragments.IMEIFragment.requestPermissions(IMEIFragment.java:107)
at com.android.project1.fragments.IMEIFragment.loadIMEI(IMEIFragment.java:80)
at com.android.project1.main.MainActivity.onCreate(MainActivity.java:108)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
And here's the relevant part of my MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDeviceCode = (TextView) findViewById(R.id.device_code);
// Initializing headless fragment
mFragment =
(IMEIFragment) getFragmentManager()
.findFragmentByTag("IMEILoader");
if (mFragment == null) {
mFragment = new IMEIFragment();
getFragmentManager().beginTransaction()
.add(mFragment, "IMEILoader").commit();
}
if (mFragment != null) {
mNumber = mFragment.loadIMEI(MainActivity.this);
mDeviceCode.setText(Html.fromHtml("<b>IMEI</b>: " + mNumber));
}
I literally had the exact same code working for over a week. Anyone knows what could be the problem?
Edit 1: The error is pointing to requestPermissions inside my fragment
Fragments should be self contained as much as possible. You are calling directly into your IMEIFragment from the activity,
Caused by: java.lang.IllegalStateException: Fragment IMEIFragment{3e80da7 IMEILoader} not attached to Activity
at android.app.Fragment.getResources(Fragment.java:805)
at android.app.Fragment.getString(Fragment.java:827)
at com.android.project1.fragments.IMEIFragment.requestPermissions(IMEIFragment.java:107)
at com.android.project1.fragments.IMEIFragment.loadIMEI(IMEIFragment.java:80)
at com.android.project1.main.MainActivity.onCreate(MainActivity.java:108)
You can't do that. Adding the fragment via a transaction from the activity is an asynchronous operation. E.g., when the commit() method completes, the fragment is not initialized. Moreover, you have no way of knowing when it's initialized. That's why it should be self contained. The fragment decides when to call loadIMEI(), not the activity.
If you really need it to be initiated by the activity, you can add a callback from the fragment to the activity like,
void onFragmentReady(Fragment f);
Or something.
And yes, onCreateView() should return something. If your fragment really doesn't have any UI at all, you don't need it to be a fragment.

RecyclerView's onClick method crashes the app

Below is my MainActivity.java (I have removed some of unnecessary code. My main activity was a Navigation Viewer activity)
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<MainStoryTile> list = new ArrayList<MainStoryTile>();
int[] image_id = { R.drawable.sample, R.drawable.sample, R.drawable.sample};
String[] name, email, mobile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = getResources().getStringArray(R.array.person_name);
email = getResources().getStringArray(R.array.person_email);
mobile = getResources().getStringArray(R.array.person_mobile);
int count = 0;
for(String NAME: name){
MainStoryTile contact = new MainStoryTile(image_id[count], NAME, email[count], mobile[count]);
count++;
list.add(contact);
}
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new MainStoryAdapter(list);
recyclerView.setAdapter(adapter);
}
#Override
public void onBackPressed() {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
return true;
}
}
Below is my Adapter class. (Note : there is an inner class)
public class MainStoryAdapter extends RecyclerView.Adapter<MainStoryAdapter.StoryViewHolder>{
ArrayList<MainStoryTile> contacts = new ArrayList<MainStoryTile>();
public MainStoryAdapter(ArrayList<MainStoryTile> contacts){
this.contacts = contacts;
}
#Override
public StoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_main,parent,false );
StoryViewHolder storyViewHolder = new StoryViewHolder(view);
return storyViewHolder;
}
#Override
public void onBindViewHolder(StoryViewHolder holder, int position) {
MainStoryTile CON = contacts.get(position);
holder.person_img.setImageResource(CON.getImage_id());
holder.person_name.setText(CON.getName());
holder.person_email.setText(CON.getEmail());
holder.person_mobile.setText(CON.getMobile());
}
#Override
public int getItemCount() {
return contacts.size();
}
public static class StoryViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView person_img;
TextView person_name, person_email, person_mobile;
public StoryViewHolder(View view){
super(view);
person_img = (ImageView) view.findViewById(R.id.person_image);
person_name = (TextView) view.findViewById(R.id.person_name);
person_email = (TextView) view.findViewById(R.id.person_email);
person_mobile = (TextView) view.findViewById(R.id.person_mobile);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Log.d("MY LOG", "sdurfhiusrhdidysdysdysdysdys r");
}
}
}
When I click on a item, my app crashes. below is error log :
03-17 15:20:38.638 28744-28744/com.storyteller.pro.storyteller E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.storyteller.pro.storyteller, PID: 28744
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4286)
at android.view.View.performClick(View.java:5242)
at android.view.View$PerformClick.run(View.java:21196)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6938)
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:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4281)
at android.view.View.performClick(View.java:5242)
at android.view.View$PerformClick.run(View.java:21196)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6938)
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:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:4277)
at android.view.ViewGroup.addView(ViewGroup.java:4127)
at android.view.ViewGroup.addView(ViewGroup.java:4068)
at android.view.ViewGroup.addView(ViewGroup.java:4041)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:247)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:114)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4281)
at android.view.View.performClick(View.java:5242)
at android.view.View$PerformClick.run(View.java:21196)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6938)
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:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
03-17 15:20:43.048 28744-28744/com.storyteller.pro.storyteller I/Process: Sending signal. PID: 28744 SIG: 9
Update: Even after I commented the following line in the view.setOnClickListener(this); in the MainStoryAdapter, my app still crashing when I click on an item.
Below is the project for those who like to see more > project zip version
I checked your project and you, why ever, define android:onClick="setContentView" in your content_main.xml layout for the CardView.
Remove that attribute and it works.

I have simple android App in android studio and it does not work

package viewbrosers.mehdi.home.mytestappviewbrowser;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button getAnswer = (Button) findViewById(R.id.getAnswerButton);
getAnswer.setOnClickListener(getAnswerListener);
}
private View.OnClickListener getAnswerListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Random randomnum = new Random();
int numToast = randomnum.nextInt(19);
numToast++;
CharSequence text = "";
switch (numToast) {
case 1:
text = getString(R.string.answer1);
break;
case 2:
text = getString(R.string.answer2);
break;
case 3:
text = getString(R.string.answer3);
break;
case 4:
text = getString(R.string.answer4);
break;
case 5:
text = getString(R.string.answer5);
break;
case 6:
text = getString(R.string.answer6);
break;
case 7:
text = getString(R.string.answer7);
break;
}
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
My error is:
Unfortunately Application has stopped and 06-05
11:31:44.131 13711-13711/? I/art﹕ Not late-enabling -Xcheck:jni
(already on) 06-05 11:31:44.208 13711-13711/? D/AndroidRuntime﹕
Shutting down VM 06-05 11:31:44.208 13711-13711/? E/AndroidRuntime﹕
FATAL EXCEPTION: main
Process: viewbrosers.mehdi.home.mytestappviewbrowser, PID: 13711
java.lang.RuntimeException: Unable to start activity ComponentInfo{viewbrosers.mehdi.home.mytestappviewbrowser/viewbrosers.mehdi.home.mytestappviewbrowser.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'boolean java.lang.String.equals(java.lang.Object)' on a null object
reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on
a null object reference
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:715)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:378)
at android.app.Activity.setContentView(Activity.java:2145)
at viewbrosers.mehdi.home.mytestappviewbrowser.MainActivity.onCreate(MainActivity.java:23)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            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) 06-05
11:31:44.218 13711-13718/? I/art﹕ Debugger is no longer active 06-05
11:32:28.690 13711-13718/viewbrosers.mehdi.home.mytestappviewbrowser
W/art﹕ Suspending all threads took: 12.748ms
Move the creation and initialization of your text variable outside of the onClick() method. Try the following code.
public class MainActivity extends Activity {
CharSequence text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = "";
Button getAnswer = (Button) findViewById(R.id.getAnswerButton);
getAnswer.setOnClickListener(getAnswerListener);
}
private View.OnClickListener getAnswerListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Random randomnum = new Random();
int numToast = randomnum.nextInt(19);
numToast++;
switch (numToast) {
case 1:
text = getString(R.string.answer1);
break;
case 2:
text = getString(R.string.answer2);
break;
case 3:
text = getString(R.string.answer3);
break;
case 4:
text = getString(R.string.answer4);
break;
case 5:
text = getString(R.string.answer5);
break;
case 6:
text = getString(R.string.answer6);
break;
case 7:
text = getString(R.string.answer7);
break;
}
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You are somewhere using equals function on string which is null.
Look at exception: 'boolean java.lang.String.equals(java.lang.Object)' on a null object
reference
Try it, may be like this.
public class MainActivity extends Activity implements OnClickListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button getAnswer = (Button) findViewById(R.id.getAnswerButton);
getAnswer.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.getAnswerButton:
//Your code
break;
}
}
}

Updating Listview ( SharedPreferences -> ArrayList) from separate Class

I would like to update my Listview in a fragmen in a onPostExecute() separate class.
The first initialization of the the Listview doas work, but wehe I call createList() again, the App crashes (NullPointerException)
Any Idea?
Main_Fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View fragmentView = inflater.inflate(R.layout.main_fragment, container, false);
StartSocketService = (Button) fragmentView.findViewById(R.id.start_socketservice);
StartSocketService.setOnClickListener(this);
StopSocketService = (Button) fragmentView.findViewById(R.id.stop_socketservice);
StopSocketService.setOnClickListener(this);
listview = (ListView) fragmentView.findViewById(R.id.listView1);
createList();
return fragmentView;
}
public void createList(){
//Reading Server IPs from SharedPreferences and put them to ListView
SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
for (int i = 0; i < 255; i++) {
if ((settings.getString("Server"+i,null)) != null) {
serverList.add(settings.getString("Server"+i, null));
Log.v("Reading IP: " +settings.getString("Server"+i, null), " from SraredPreferrences at pos.: "+i );
}
}
//Initializing listView
final StableArrayAdapter adapter = new StableArrayAdapter(getActivity(),android.R.layout.simple_list_item_1, serverList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
final String item = (String) parent.getItemAtPosition(position);
view.animate().setDuration(2000).alpha(0).withEndAction(new Runnable() {
#Override
public void run() {
serverList.remove(item);
adapter.notifyDataSetChanged();
view.setAlpha(1);
}
});
}
});
}
Some class:
async_cient = new AsyncTask<Void, Void, Void>() {
...
protected void onPostExecute(Void result) {
Toast.makeText(mContext, "Scan Finished", Toast.LENGTH_SHORT).show();
Main_Fragment cList = new Main_Fragment();
cList.createList();
super.onPostExecute(result);
}
};
Log:
07-29 14:42:46.428 3382-3382/de.liquidbeam.LED.control D/AndroidRuntime﹕ Shutting down VM
07-29 14:42:46.428 3382-3382/de.liquidbeam.LED.control W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41549ba8)
07-29 14:42:46.438 3382-3382/de.liquidbeam.LED.control E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: de.liquidbeam.LED.control, PID: 3382
java.lang.NullPointerException
at de.liquidbeam.LED.control.fragments.Main_Fragment.createList(Main_Fragment.java:56)
at de.liquidbeam.LED.control.background.UDP_Discover$1.onPostExecute(UDP_Discover.java:94)
at de.liquidbeam.LED.control.background.UDP_Discover$1.onPostExecute(UDP_Discover.java:57)
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)
07-29 14:47:46.591 3382-3382/de.liquidbeam.LED.control I/Process﹕ Sending signal. PID: 3382 SIG: 9
Lines:
56 : SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
94 : cList.createList();
57: async_cient = new AsyncTask<Void, Void, Void>() {
You creating a new instance of your fragment with no context (activity) to run in. So
the line
SharedPreferences settings = getActivity().getSharedPreferences("Found_Devices", 0);
Tries to get his activity but there is no activity where the fragment lives in ;)

AlertDialog in arrayAdapter not working

I'm trying to get my alertDialog working in an arrayAdapter. This is how my function looks like.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Noodnummers currentNoodnummer = noodnummers.get(position);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(layoutResourceId, parent, false);
TextView txt_noodnummer_name = (TextView) rowView.findViewById(R.id.txt_noodnummer_name);
txt_noodnummer_name.setText(currentNoodnummer.naam);
TextView txt_noodnummer_telefoon = (TextView) rowView.findViewById(R.id.txt_noodnummer_telefoon);
txt_noodnummer_telefoon.setText(Html.fromHtml(currentNoodnummer.telefoonNummer));
txt_noodnummer_telefoon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
//To change body of implemented methods use File | Settings | File Templates.
try {
new AlertDialog.Builder(this)
.setTitle("")
.setMessage("Bent u zeker dat u" + currentNoodnummer.telefoonNummer + "wilt bellen?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
String uri = currentNoodnummer.telefoonNummer;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uri));
v.getContext().startActivity(intent);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
} catch (ActivityNotFoundException activityException) {
Log.e("genkonstage", "Call failed", activityException);
}
}
});
return rowView;
}
The first problem is, that new AlertDialog.Builder(this) is given me an error on the word this. Then I found that I maybe should use a context. But when I say new AlertDialog.Builder(context) I get no error but when I click the app crashes.
Can someone help me with this?
EDIT
06-18 10:56:20.689 12980-12980/be.appmax.genkOnStage E/AndroidRuntime: FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
at android.view.ViewRootImpl.setView(ViewRootImpl.java:571)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:246)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at android.app.AlertDialog$Builder.show(AlertDialog.java:951)
at be.appmax.genkOnStage.adapters.NoodnummersArrayAdapter$1.onClick(NoodnummersArrayAdapter.java:57)
at android.view.View.performClick(View.java:4204)
at android.view.View$PerformClick.run(View.java:17355)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Creation of arrayAdapter inside NoodnummersActivity
ListView listView = (ListView) findViewById(R.id.listViewNoodnummers);
//addList(noodnummersArrayList, listView);
NoodnummersArrayAdapter adapter = new NoodnummersArrayAdapter(getBaseContext(), R.layout.noodnummers_list, noodnummersArrayList);
// fill the listview with adapter.
listView.setAdapter(adapter);
setListViewHeightBasedOnChildren(listView);
"Never" use getBaseContext()! From a Google Engineer
Try with NoodnummersActivity.this
NoodnummersArrayAdapter adapter = new NoodnummersArrayAdapter(NoodnummersActivity.this, R.layout.noodnummers_list, noodnummersArrayList);
and then try with
new AlertDialog.Builder(context)
By the way, I suggest at the beginning of your activity to define a private field with the context. I found this suggestion here somewhere and I find it awesome:
public class MyActivity extends Activity {
private Context context = MyActivity.this;
}
in this way you can use "context" without any worries.
Use this method for context:
private Context getDialogContext() {
Context context;
if (getParent() != null)
context = getParent();
else
context = this;
return context;
}
try this it will work.

Categories