This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am a beginner at android studio, I have a mission to redesign the app. I use the Fragment. But when I run my app, it has stopped and there is no error in my Gradle. I looked for many website to solve my question, but still have no idea.
I have some questions below.
How can I fix the java.lang.RuntimeException (NULL Pointer Exception) ?
09-30 02:59:56.574 17706-17706/? E/memtrack: Couldn't load memtrack module (No such file or directory)
09-30 02:59:56.574 17706-17706/? E/android.os.Debug: failed to load memtrack module: -2
09-30 02:59:56.996 17722-17722/? E/memtrack: Couldn't load memtrack module (No such file or directory)
09-30 02:59:56.996 17722-17722/? E/android.os.Debug: failed to load memtrack module: -2
09-30 02:59:57.090 17734-17734/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: tw.com.flag.parking22, PID: 17734
java.lang.RuntimeException: Unable to start activity ComponentInfo{tw.com.flag.parking22/tw.com.flag.parking22.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
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: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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at tw.com.flag.parking22.MainActivity.init(MainActivity.java:102)
at tw.com.flag.parking22.MainActivity.onCreate(MainActivity.java:71)
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:2387)
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: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)
09-30 02:59:57.211 1160-1160/? E/EGL_emulation: tid 1160: eglCreateSyncKHR(1865): error 0x3004 (EGL_BAD_ATTRIBUTE)
09-30 03:02:15.409 2159-19872/com.google.android.gms E/Herrevad: [350] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:02:15.445 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:02:15.445 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=NetworkReportService requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=3600000 target_class=com.google.android.gms.common.stats.net.NetworkReportService runtime=1506742923454 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=7200000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:02:15.446 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.common.stats.net.NetworkReportService{u=0 tag="NetworkReportService" trigger=window{period=7200s,flex=3600s,earliest=5988s,latest=9588s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=2388s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:02:15.474 1170-1578/? E/Drm: Failed to find drm plugin
09-30 03:02:15.563 2159-2680/com.google.android.gms E/Volley: [129] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=AggregationTaskTag requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=600000 target_class=com.google.android.gms.checkin.EventLogService runtime=1506741123628 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=1800000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.checkin.EventLogService{u=0 tag="AggregationTaskTag" trigger=window{period=1800s,flex=600s,earliest=1787s,latest=2387s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=587s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:03:37.417 1170-1578/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000
09-30 03:30:15.406 2159-21157/com.google.android.gms E/Herrevad: [355] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:30:15.511 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.518 2159-21168/com.google.android.gms E/ZappLogOperation: Unable to bind to Phonesky
09-30 03:30:15.526 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.526 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.551 2159-2678/com.google.android.gms E/Volley: [127] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:30:15.572 1170-1578/? E/Drm: Failed to find drm plugin
09-30 03:30:22.524 2159-2159/com.google.android.gms E/ActivityThread: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection ctn#2f714ea6 that was originally bound here
android.app.ServiceConnectionLeaked: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection ctn#2f714ea6 that was originally bound here
at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1077)
at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:971)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1774)
at android.app.ContextImpl.bindService(ContextImpl.java:1757)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at com.google.android.gms.chimera.container.zapp.ZappLogOperation.onHandleIntent(:com.google.android.gms#11509280:1)
at com.google.android.chimera.IntentOperation.onHandleIntent(:com.google.android.gms#11509280:2)
at bwy.run(:com.google.android.gms#11509280:10)
at bwv.run(:com.google.android.gms#11509280:14)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=AggregationTaskTag requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=600000 target_class=com.google.android.gms.checkin.EventLogService runtime=1506743055606 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=1800000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.checkin.EventLogService{u=0 tag="AggregationTaskTag" trigger=window{period=1800s,flex=600s,earliest=1199s,latest=1799s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=0s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:44:15.637 2159-21184/com.google.android.gms E/Herrevad: [371] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:44:15.755 2159-2676/com.google.android.gms E/Volley: [126] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:46:13.425 1171-1171/? E/installd: eof
09-30 03:46:13.425 1171-1171/? E/installd: failed to read size
Here is the main activity code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager =(ViewPager) findViewById(R.id.pager);
PagerAdapter padapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(padapter);
//--------------------------------------------------------------------
init();
Action();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
}
else {
}
}
private void init(){
System.out.println("start---------------------");
textView_userIDVal = (TextView) findViewById(R.id.textView_userIDVal);
textView_parkingNoVal = (TextView) findViewById(R.id.textView_parkingNoVal);
textView_pillarNoVal = (TextView) findViewById(R.id.textView_pillarNoVal);
textView_colorVal = (TextView) findViewById(R.id.textView_colorVal);
imageView = (ImageView) findViewById(R.id.imageView);
button_space = (Button) findViewById(R.id.button_space);
button_scan = (Button) findViewById(R.id.button_scan);
button_find = (Button) findViewById(R.id.button_find);
simpleDateFormat = new SimpleDateFormat("MM/dd 'at' HH");
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
userID = Build.SERIAL;
//-------------error start next----------------
textView_userIDVal.setText("User ID : " + userID);
}
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 200);
}
sharedPreferences = getSharedPreferences("Data", 0);
if(sharedPreferences.contains("parkingNum") && sharedPreferences.contains("time")) {
parkingNumtmp = sharedPreferences.getString("parkingNum", "");
textView_parkingNoVal.setText("Parking No. : " + parkingNumtmp + "\t(" + sharedPreferences.getString("time", "") + ")");
}
builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder_timeout = new AlertDialog.Builder(this);
builder_timeout.setTitle("REMIND");
builder_timeout.setMessage("Do you find your car ?");
builder_timeout.setCancelable(false);
builder_timeout.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
json_data = new JSONObject();
json_data.put("MT", "timeout");
json_data.put("PlaceMac", parkingNumtmp);
json_data.put("UserMac", userID);
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", false);
isCloseScreen = false;
} catch (JSONException e) {
e.printStackTrace();
}
thread = new Thread(TCP);
thread.start();
timer_count = 0;
startFlag = false;
}
});
builder_timeout.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
maxTime = 10;
maxTime = maxTime / 2;
timer_count = 0;
startFlag = true;
}
});
}
private void Action(){
button_space.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
json_data = new JSONObject();
json_data.put("MT", "count");
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", true);
//System.out.println(json_write + "\n");
} catch (JSONException e) {
e.printStackTrace();
}
thread = new Thread(TCP);
thread.start();
/*builder.setTitle("INFORMATION");
builder.setMessage("All : " + "\nNow : " );
AlertDialog alertDialog = builder.create();
alertDialog.show();*/
}
});
button_scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ScanActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
});
button_find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(parkingNumtmp != null) {
try {
maxTime = 10;
json_data = new JSONObject();
json_data.put("MT", "search");
json_data.put("PlaceMac", parkingNumtmp);
json_data.put("UserMac", userID);
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", true);
//System.out.println(json_write + "\n");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Don't close the screen before you find your car ! ", Toast.LENGTH_LONG).show();
thread = new Thread(TCP);
thread.start();
}
else {
builder.setTitle("WARNING");
builder.setMessage("Please scan QRcode first!");
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
if(data != null) {
final Barcode barcode = data.getParcelableExtra("barcode");
parkingNumtmp = barcode.displayValue;
Date date = new Date();
final String time = simpleDateFormat.format(date);
sharedPreferences.edit().putString("parkingNum", parkingNumtmp).putString("time", time).commit();
textView_parkingNoVal.post(new Runnable() {
#Override
public void run() {
textView_parkingNoVal.setText("Parking No. : " + parkingNumtmp + "\t(" + time +")");
}
});
}
}
}
About Fragment. Is there any setting I have to do when I receive data form sever?
I want to put the received data to TextView in the another view .
Your init() function is probably try to find views inside fragments in view pager. However, at that moment, the fragments are not inflated yet, so your views in the activity are null and trying to do operation on them gives NPE. You should use onCreateView() of Fragment classes to find those views. Then you may notify main activity via callback mechanism.
For example, create FirstFragment as follows:
public class FirstFragment extends Fragment {
private OnFirstFragmentReadyListener callback;
#Override
public void onAttach(Context context) {
super.onAttach(context);
// This makes sure that the container activity has implemented the callback.
try {
callback = (OnFirstFragmentReadyListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnFirstFragmentReadyListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_first, container, false);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Notify the parent activity that the fragment is inflated.
callback.onFirstFragmentReady();
}
public interface OnFirstFragmentReadyListener {
void onFirstFragmentReady();
}
}
Let the layout of FirstFragment as follows (referenced above as fragment_first):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/first_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Assume we created two more similar fragment classes named as SecondFragment and ThirdFragment. Then the activity should be like this:
public class MainActivity extends AppCompatActivity implements FirstFragment.OnFirstFragmentReadyListener,
SecondFragment.OnSecondFragmentReadyListener, ThirdFragment.OnThirdFragmentReadyListener {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager =(ViewPager) findViewById(R.id.pager);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
// Don't call these functions here, spread them into callbacks.
// init();
// Action();
}
#Override
public void onFirstFragmentReady() {
TextView firstTextView = (TextView) findViewById(R.id.first_label);
...
// Now you have the views from FirstFragment instance.
// You can now call setText() or setOnClickListener() here.
}
#Override
public void onSecondFragmentReady() {
TextView secondTextView = (TextView) findViewById(R.id.second_label);
...
// Now you have the views from SecondFragment instance.
// You can now call setText() or setOnClickListener() here.
}
#Override
public void onThirdFragmentReady() {
TextView thirdTextView = (TextView) findViewById(R.id.third_label);
...
// Now you have the views from ThirdFragment instance.
// You can now call setText() or setOnClickListener() here.
}
}
Although this code works, this may not be the best way. I think it is better to do operations on views like setting texts or assigning OnClickListeners in fragments itself. If you need to notify a fragment after an action happened in the parent activity, you can implement public methods inside fragments and you can call them from the parent activity when needed.
In fragment you should call the function in onCreateView function(reason as mention by #Mehmed) which is something like below:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.your_fragment, container, false);
//all findViewById;
TextView yourTextView = (Text)view.findViewById(R.id.yourTextView);
//here call for your function
init();
// any other function goes here
return view;
}
Related
Everybody,
I'm trying to record audio.
The audio is record perfectly when record button is clicked.
I try to stop the record and the app crashing immediately after the stop button is clicked.
Can you please help me on fixing this code so i could continue building my project.
Here's part of the code:
public class window2 extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
Spinner spinner;//choice between record and Speech-2-text.
Button play,stop,record;//record, stop and replay buttons.
String outputFile;//the record file.
MediaRecorder myAudioRecorder;//the record method.
int reRecord = 0;//reRecord value.
int pathVal = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_window2);
spinner = findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);//upon change between record and S2T.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor edit = sharedPreferences.edit();
if( sharedPreferences.getInt("pathVal",0) == 0)
edit.putInt("pathVal",1);
else {
pathVal = sharedPreferences.getInt("pathVal", pathVal);
edit.putInt("pathVal",pathVal+1);
}
pathVal = sharedPreferences.getInt("pathVal", 0);
edit.commit();
//3 buttons for record,stop and replay.
play = findViewById(R.id.button14);
stop = findViewById(R.id.button13);
record = findViewById(R.id.button11);
//to immune issues that may start if the buttons are enabled.
stop.setEnabled(false);
play.setEnabled(false);
//the file of recording.
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+pathVal+".3gp";
//record settings.
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
myAudioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
//record button click.
record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play.setEnabled(false);
try{
//if we want to re record.
if(reRecord == 1)
{
//we build the settings again.
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
}
//prepare and start methods.
myAudioRecorder.prepare();
myAudioRecorder.start();
}catch (IllegalStateException ise) {
//something
}catch (IOException ioe){
//something
}
record.setEnabled(false);
stop.setEnabled(true);
Toast.makeText(window2.this, "Recording...", Toast.LENGTH_SHORT).show();
}
});
//stop button click.
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myAudioRecorder.stop();
myAudioRecorder.reset();
reRecord = 1;
myAudioRecorder = null;
record.setEnabled(true);
stop.setEnabled(false);
play.setEnabled(true);
Toast.makeText(window2.this, "Recorded!", Toast.LENGTH_SHORT).show();
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(outputFile);
mediaPlayer.prepare();
mediaPlayer.start();
Toast.makeText(window2.this, "Playing.", Toast.LENGTH_SHORT).show();
} catch (Exception e){
//something
}
}
});
}
public void OpenWindow4(View view)
{
Spinner spinner = findViewById(R.id.spinner3);
String SpinTxt = spinner.getSelectedItem().toString();
EditText edit2 = findViewById(R.id.editText);
String editTextTxt = edit2.getText().toString();
Intent intent = new Intent(this,window4.class);
intent.putExtra("THE_TEXT",editTextTxt);
intent.putExtra("SPIN_CHOICE",SpinTxt);
startActivity(intent);
}
public void OpenWindow4Speech(View view)
{
Spinner spinner = findViewById(R.id.spinner4);
String SpinTxt = spinner.getSelectedItem().toString();
EditText edit2 = findViewById(R.id.editText2);
String editTextTxt = edit2.getText().toString();
Intent intent = new Intent(this,window4.class);
intent.putExtra("THE_RECORD",outputFile);
intent.putExtra("SPIN_CHOICE",SpinTxt);
intent.putExtra("THE_TEXT",editTextTxt);
startActivity(intent);
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String item = adapterView.getItemAtPosition(i).toString();
if (item.equals("S2T"))
{
Intent intent = new Intent(this,windows2B.class);
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
and here is the logcat:
01-13 08:42:27.105 1031-1031/com.example.simplenigal.prealphabuilt V/MediaRecorder: prepare
01-13 08:42:27.105 1031-1031/com.example.simplenigal.prealphabuilt V/MediaRecorder: start
01-13 08:42:27.105 1031-1031/com.example.simplenigal.prealphabuilt E/MediaRecorder: start failed: -38
01-13 08:42:27.757 1031-1038/com.example.simplenigal.prealphabuilt I/art: Do partial code cache collection, code=115KB, data=106KB
01-13 08:42:27.757 1031-1038/com.example.simplenigal.prealphabuilt I/art: After code cache collection, code=115KB, data=106KB
01-13 08:42:27.757 1031-1038/com.example.simplenigal.prealphabuilt I/art: Increasing code cache capacity to 512KB
01-13 08:42:27.759 1031-1038/com.example.simplenigal.prealphabuilt I/art: Compiler allocated 6MB to compile void android.view.ViewRootImpl.performTraversals()
01-13 08:42:31.382 1031-1031/com.example.simplenigal.prealphabuilt I/ViewRootImpl: ViewRoot's Touch Event : ACTION_DOWN
01-13 08:42:31.452 1031-1031/com.example.simplenigal.prealphabuilt I/ViewRootImpl: ViewRoot's Touch Event : ACTION_UP
01-13 08:42:31.462 1031-1031/com.example.simplenigal.prealphabuilt V/MediaRecorder: stop
01-13 08:42:31.462 1031-1031/com.example.simplenigal.prealphabuilt E/MediaRecorder: stop called in an invalid state: 0
01-13 08:42:31.463 1031-1031/com.example.simplenigal.prealphabuilt D/AndroidRuntime: Shutting down VM
01-13 08:42:31.468 1031-1031/com.example.simplenigal.prealphabuilt E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.simplenigal.prealphabuilt, PID: 1031
java.lang.IllegalStateException
at android.media.MediaRecorder.native_stop(Native Method)
at android.media.MediaRecorder.stop(MediaRecorder.java:896)
at com.example.simplenigal.prealphabuilt.window2$2.onClick(window2.java:102)
at android.view.View.performClick(View.java:5624)
at android.view.View$PerformClick.run(View.java:22441)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6316)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
thanks to every one who paying attention and helping.
Still looking for help
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 = ....
The problem is as follows. I have a login activity (in Android Studio) which worked fine a few days before. I don't remember changing anything but when I run this one the previous time the app closed right after I clicked the login button. The last thing indicated was the toast about pre-execution of AsyncTask.
And I can't understand why there could be a NullPointerException.
I have almost the same code for my signup activity and it works fine.
Here is the log:
05-28 16:04:52.395 1218-1232/system_process V/WindowManager﹕ addAppToken: AppWindowToken{5d89eb token=Token{23ccc93a ActivityRecord{2fe54865 u0 utanashati.reminder/.HomepageActivity t17}}} to stack=1 task=17 at 1
05-28 16:04:52.407 19927-19927/utanashati.reminder D/AndroidRuntime﹕ Shutting down VM
05-28 16:04:52.408 19927-19927/utanashati.reminder E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: utanashati.reminder, PID: 19927
java.lang.RuntimeException: Unable to start activity
ComponentInfo{utanashati.reminder/utanashati.reminder.HomepageActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' 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 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at utanashati.reminder.HomepageActivity.onCreate(HomepageActivity.java:55)
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)
05-28 16:04:52.410 1218-1232/system_process W/ActivityManager﹕ Force finishing activity 1 utanashati.reminder/.HomepageActivity
05-28 16:04:52.411 1218-1232/system_process W/ActivityManager﹕ Force finishing activity 2 utanashati.reminder/.LoginActivity
EDIT 1
I had my eyes opened, the problem is not with LoginActivity, but with HomepageActivity. Here is the code:
import ...
public class HomepageActivity extends Activity implements AdapterView.OnItemSelectedListener {
protected EditText mAddTaskText;
protected Spinner mPrioritySpinner;
protected Button mAddTaskButton;
protected int intPriority = 0;
protected String taskText;
protected Timestamp taskTimestamp;
protected Task userTask;
protected JsonGenerator taskJSON;
#Override
protected void onCreate(Bundle savedInstanceState) { // Starts activity. The state can be restored from savedInstanceState
super.onCreate(savedInstanceState); // Calls the superclass method (IMPORTANT)
setContentView(R.layout.activity_homepage); // Sets layout from activity_homepage.xml
mPrioritySpinner = (Spinner) findViewById(R.id.prioritySpinner); // Creates an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.priorityList, android.R.layout.simple_spinner_item); // Specifies the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Applies the adapter to the spinner
mPrioritySpinner.setAdapter(adapter);
mPrioritySpinner.setOnItemSelectedListener(this);
mAddTaskText = (EditText) findViewById(R.id.addTaskEditText); // Finds View by its id in .xml file
mAddTaskButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(HomepageActivity.this, "Done!", Toast.LENGTH_LONG).show();
Calendar taskCalendar = Calendar.getInstance(); // Creates new calendar
long taskTime = taskCalendar.getTimeInMillis(); // Gets time in milliseconds
taskTimestamp = new Timestamp(taskTime); // Creates new Timestamp
taskText = mAddTaskText.getText().toString(); // Gets description of the task
userTask.setDate(taskTimestamp); // Sets date
userTask.setText(taskText); // Sets text
/* Creating JsonGenerator */
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(taskJSON, userTask);
}
catch (IOException e) {
Toast.makeText(HomepageActivity.this, "Could not create JSON", Toast.LENGTH_LONG).show();
}
/* Getting out email and password */
String userPassword = ((EmailPassword) HomepageActivity.this.getApplication()).getPassword();
String userEmail = ((EmailPassword) HomepageActivity.this.getApplication()).getUserEmail();
Toast.makeText(HomepageActivity.this, userEmail + " " + userPassword, Toast.LENGTH_LONG).show();
/* HTTP stuff */
HttpPoster get = new HttpPoster();
get.execute(userEmail, userPassword, taskJSON.toString());
}
});
}
public int getData (String username, String password, String taskJSON) {
try {
HttpPost httpPost = new HttpPost("http://something.com/" + username + "/tasks");
String dataToEncode = username + ":" + password;
String encodedData = Base64.encodeToString(dataToEncode.getBytes(), Base64.NO_WRAP);
httpPost.setHeader("Authorization", encodedData);
try {
StringEntity taskEntity = new StringEntity(taskJSON, "UTF-8");
httpPost.setEntity(taskEntity);
}
catch (UnsupportedEncodingException e) {
Toast.makeText(HomepageActivity.this, "Unsupported encoding", Toast.LENGTH_LONG).show();
}
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
return 1;
}
else if (statusCode == 404) { return 2; }
else if (statusCode == 500) { return 3; }
else if (statusCode == 409) { return 4; }
else { return statusCode; }
}
catch (IOException e) {
e.printStackTrace();
}
return 0;
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
String priority = parent.getItemAtPosition(pos).toString(); // Gets chosen priority
Toast.makeText(HomepageActivity.this, priority, Toast.LENGTH_LONG).show();
while (!((priority.equals("Low")) || (priority.equals("Medium")) || (priority.equals("High")))) {
Toast.makeText(HomepageActivity.this, "Something bad happened. Try to choose again", Toast.LENGTH_LONG).show();
}
if (priority.equals("Low")) {
intPriority = 0;
}
else if (priority.equals("Medium")) {
intPriority = 1;
}
else if (priority.equals("High")) {
intPriority = 2;
}
userTask.setPriority(intPriority); // Sets chosen priority
}
public void onNothingSelected(AdapterView<?> parent) {
userTask.setPriority(intPriority); // Sets default priority ("0")
}
public class HttpPoster extends AsyncTask<String, Void, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Integer doInBackground(String... params) {
return getData(params[0], params[1], params[3]);
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (result == 1) {
Toast.makeText(HomepageActivity.this, "Login successful", Toast.LENGTH_LONG).show();
Intent takeUserHome = new Intent(HomepageActivity.this, HomepageActivity.class);
startActivity(takeUserHome);
}
else if (result == 2) {
Toast.makeText(HomepageActivity.this, "No such user", Toast.LENGTH_LONG).show();
}
else if (result == 3) {
Toast.makeText(HomepageActivity.this, "Internal server error: unable to send email", Toast.LENGTH_LONG).show();
}
else if (result == 4) {
Toast.makeText(HomepageActivity.this, "Task already exists", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(HomepageActivity.this, result.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
And XML file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="utanashati.testapp.HomepageActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Add a new task..."
android:id="#+id/addTaskEditText"
android:nestedScrollingEnabled="false"
android:minLines="1"
android:maxLines="1" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/prioritySpinner"
android:layout_alignRight="#+id/addTaskButton"
android:layout_alignEnd="#+id/addTaskButton"
android:layout_below="#+id/addTaskEditText" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add task"
android:id="#+id/addTaskButton"
android:layout_below="#+id/prioritySpinner"
android:layout_centerHorizontal="true" />
</RelativeLayout>
It seems the button you are invoking is not in the layout you are using in setContentView(R.layout.your_layout)
Check it.
mAddTaskButton is null because you never initialize it with:
mAddTaskButton = (Button) findViewById(R.id.addTaskButton);
before you call mAddTaskButton.setOnClickListener().
Check out this solution. It worked for me.....
Check the id of the button for which the error is raised...it may be the same in any one of the other page in your app.
If yes, then change the id of them and then the app runs perfectly.
I was having two same button id's in two different XML codes....I changed the id. Now it runs perfectly!!
Hope it works
That true,Mustafa....its working..its point to two layout
setContentView(R.layout.your_layout)
v23(your_layout).
You should take Button both activity layout...
solve this problem successfully
Check whether you have matching IDs in both Java and XML
Just define the button as lateinit var at top of your class:
lateinit var buttonOk: Button
When you want to use a button in another layout you should define it in that layout. For example if you want to use button in layout which name is 'dialogview', you should write:
buttonOk = dialogView.findViewById<Button>(R.id.buttonOk)
After this you can use setonclicklistener for the button and you won't have any error.
You can see correct answer of this question: Android Kotlin findViewById must not be null
Make sure that while using :
Button "varName" =findViewById("btID");
you put in the right "btID". I accidentally put in the id of a button from another similar activity and it showed the same error. Hope it helps.
Got the same error,
CHECK THIS : MINOR SILLY MISTAKE
check findviewbyid(R.id.yourID);
If you have put the id correct or not.
i had the same problem and it seems like i didn't initiate the button used with click listener, in other words id didn't te
Placing setOnClickListener in onStart method solved the problem for me.
Checkout "Android Lifecycle concept" for further clarification
mAddTaskButton.setOnClickListener(new View.OnClickListener()
you have a click listner but you haven't initialized the mAddTaskButton with your layout binding
Please check whether you have two Layout folder (e.g Layout & Layout-V21). The XML file should be same in both folders. That was the case for me.
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 ;)
I'm unable to call notifyDataSetChanged without the application crashing.
ListFragment class:
public class ServerListFragment extends ListFragment implements OnTaskCompleteListener {
private AsyncTaskManager mAsyncTaskManager;
private ServersDataSource datasource;
private ArrayList<Server> servers;
private boolean paused = false;
private boolean generateList = true;
private String operation = "";
/**
* The serialization (saved instance state) Bundle key representing the
* activated item position. Only used on tablets.
*/
private static final String STATE_ACTIVATED_POSITION = "activated_position";
/**
* The fragment's current callback object, which is notified of list item
* clicks.
*/
private Callbacks mCallbacks = sDummyCallbacks;
/**
* The current activated item position. Only used on tablets.
*/
private int mActivatedPosition = ListView.INVALID_POSITION;
/**
* A callback interface that all activities containing this fragment must
* implement. This mechanism allows activities to be notified of item
* selections.
*/
public interface Callbacks {
/**
* Callback for when an item has been selected.
*/
public void onItemSelected(String id);
}
/**
* A dummy implementation of the {#link Callbacks} interface that does
* nothing. Used only when this fragment is not attached to an activity.
*/
private static Callbacks sDummyCallbacks = new Callbacks() {
#Override
public void onItemSelected(String id) {
}
};
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ServerListFragment() {
}
/*
* Default list adapter
*/
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// retainInstance and survive on configuration changes (rotation)
setRetainInstance(true);
// Create manager and set this activity as context and listener
mAsyncTaskManager = new AsyncTaskManager(getActivity(), this);
// Handle task that can be retained before
mAsyncTaskManager.handleRetainedTask(getActivity().getLastNonConfigurationInstance());
// start async task
getServersServices();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Restore the previously serialized activated item position.
if (savedInstanceState != null
&& savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
setActivatedPosition(savedInstanceState
.getInt(STATE_ACTIVATED_POSITION));
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Activities containing this fragment must implement its callbacks.
if (!(activity instanceof Callbacks)) {
throw new IllegalStateException(
"Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
}
#Override
public void onDetach() {
super.onDetach();
// Reset the active callbacks interface to the dummy implementation.
mCallbacks = sDummyCallbacks;
}
#Override
public void onListItemClick(ListView listView, View view, int position,
long id) {
super.onListItemClick(listView, view, position, id);
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mActivatedPosition != ListView.INVALID_POSITION) {
// Serialize and persist the activated item position.
outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
}
}
/**
* Turns on activate-on-click mode. When this mode is on, list items will be
* given the 'activated' state when touched.
*/
public void setActivateOnItemClick(boolean activateOnItemClick) {
// When setting CHOICE_MODE_SINGLE, ListView will automatically
// give items the 'activated' state when touched.
getListView().setChoiceMode(
activateOnItemClick ? ListView.CHOICE_MODE_SINGLE
: ListView.CHOICE_MODE_NONE);
}
private void setActivatedPosition(int position) {
if (position == ListView.INVALID_POSITION) {
getListView().setItemChecked(mActivatedPosition, false);
} else {
getListView().setItemChecked(position, true);
}
mActivatedPosition = position;
}
public void notifyDataSetChanged() {
((BaseAdapter) getListAdapter()).notifyDataSetChanged();
}
public void getServersServices() {
datasource = new ServersDataSource(getActivity());
datasource.open();
datasource.emptyServersTable();
operation = "GetSevers";
mAsyncTaskManager.setupTask(new Task(getResources(), getActivity(), getResources().getString(R.string.refreshing), operation, 0, ""));
}
public void onTaskComplete(Task task) {
if (task.isCancelled()) {
// Report about cancel
if (DEBUG) Log.i(TAG, "ServersStatus onTaskComplete task cancel");
} else {
// Get result
Boolean result = null;
try {
result = task.get();
} catch (Exception e) {
if (DEBUG) Log.e(TAG, "ServersStatus onTaskComplete error: " + e.toString());
}
// Report about result
servers = datasource.getAllServers();
if(servers.size() > 0 && generateList){
DummyContent.setContext(servers);
notifyDataSetChanged();
}
operation = "";
}
generateList = true;
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
if (message.equals("Refresh list")) {
servers = datasource.getAllServers();
getServersServices();
}
}
};
}
Error log:
> 09-30 15:15:39.360: E/AndroidRuntime(14322): FATAL EXCEPTION: main
> 09-30 15:15:39.360: E/AndroidRuntime(14322):
> java.lang.NullPointerException 09-30 15:15:39.360:
> E/AndroidRuntime(14322): at
> com.ww.www.ServerListFragment.notifyDataSetChanged(ServerListFragment.java:307)
> 09-30 15:15:39.360: E/AndroidRuntime(14322): at
> com.ww.www.ServerListFragment.onTaskComplete(ServerListFragment.java:385)
> 09-30 15:15:39.360: E/AndroidRuntime(14322): at
> com.ww.www.core.AsyncTaskManager.onComplete(AsyncTaskManager.java:67)
> 09-30 15:15:39.360: E/AndroidRuntime(14322): at
> com.ww.www.core.Task.onPostExecute(Task.java:330) 09-30 15:15:39.360:
> E/AndroidRuntime(14322): at
> com.ww.www.core.Task.onPostExecute(Task.java:1) 09-30 15:15:39.360:
> E/AndroidRuntime(14322): at
> android.os.AsyncTask.finish(AsyncTask.java:631) 09-30 15:15:39.360:
> E/AndroidRuntime(14322): at
> android.os.AsyncTask.access$600(AsyncTask.java:177) 09-30
> 15:15:39.360: E/AndroidRuntime(14322): at
> android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
> 09-30 15:15:39.360: E/AndroidRuntime(14322): at
> android.os.Handler.dispatchMessage(Handler.java:99) 09-30
> 15:15:39.360: E/AndroidRuntime(14322): at
> android.os.Looper.loop(Looper.java:137) 09-30 15:15:39.360:
> E/AndroidRuntime(14322): at
> android.app.ActivityThread.main(ActivityThread.java:4898) 09-30
> 15:15:39.360: E/AndroidRuntime(14322): at
> java.lang.reflect.Method.invokeNative(Native Method) 09-30
> 15:15:39.360: E/AndroidRuntime(14322): at
> java.lang.reflect.Method.invoke(Method.java:511) 09-30 15:15:39.360:
> E/AndroidRuntime(14322): at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1008)
> 09-30 15:15:39.360: E/AndroidRuntime(14322): at
> com.android.internal.os.ZygoteInit.main(ZygoteInit.java:775) 09-30
> 15:15:39.360: E/AndroidRuntime(14322): at
> dalvik.system.NativeStart.main(Native Method)
I can see that you are using the example that eclipse gives regarding master detail flow with the DummyContent class, but you have removed this peace of code which is vital for this code to work
setListAdapter(new ArrayAdapter<DummyContent.DummyItem>(getActivity(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
DummyContent.ITEMS));
put it back in the onCreate
Unable to see adapter in your code. Please setAdapter.
I don'd see ListFragment.setListAdapter being called anywhere. Which is the reason for the crash noticed here.
public void notifyDataSetChanged() {
((BaseAdapter) getListAdapter()).notifyDataSetChanged();
}
Here, you are trying to get the List adapter and call notifyDataSetChanged(). Since there's no list adapter, it will result in NPE.
The problem is probably in this method:
public void notifyDataSetChanged() {
((BaseAdapter) getListAdapter()).notifyDataSetChanged();
}
I guess that getListAdapter() returns null because I cant see that you are setting any adapter to this ListFragment anywhere.