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;
}
I'm struggling with an Android activity lifecycle issue: When I return to an activity from its child activity, all the instance variables are null, even though they should have been initialized in the onCreate() method of the activity. As you can see below, the SignSearchActivity works fine as long as I stay on the activity. Orientation changes are no problem. As soon as I navigate to the child activity SignSearch_Video_Activity and navigate back up again, a NullPointerException is thrown in the SignSearchActivity.onStart() method. As you can see from the log output the SignSearchActivity.onCreate() method is actually called before the onStart() method. I've had a very similar issue in the SignSearchActivity.onPostExecute() method, but I was able to find a workaround for that (see FIXME code below). Now, I'm really stuck.
Any help very much appreciated.
Best
Matthias
Searching for a string triggers normal lifecycle flow (instance hashCode at the end)
03-20 17:34:25.187 5980-5980/de.foo.bar.baz D/SignBrowserUIFragment: onPause
03-20 17:34:25.201 5980-5980/de.foo.bar.baz D/SignSearchActivity: onCreate() 81236595
03-20 17:34:25.250 5980-5980/de.foo.bar.baz D/SignSearchActivity: setupRecyclerView() 81236595
03-20 17:34:25.251 5980-5980/de.foo.bar.baz D/SignSearchActivity: setupSupportActionBar() 81236595
03-20 17:34:25.252 5980-5980/de.foo.bar.baz D/SignSearchActivity: initSignSearchTaskFragment() 81236595
03-20 17:34:25.253 5980-5980/de.foo.bar.baz D/SignSearchActivity: onStart() 81236595
03-20 17:34:25.254 5980-5980/de.foo.bar.baz D/SignSearchActivity: onPreExecute 81236595
03-20 17:34:25.257 5980-6295/de.foo.bar.baz D/SignDAO: Opening database.
03-20 17:34:25.261 5980-6295/de.foo.bar.baz I/SQLiteAssetHelper: successfully opened database signs.db
03-20 17:34:25.262 5980-6295/de.foo.bar.baz D/SignDAO: Reading signs with name_locale_de like: ma
03-20 17:34:25.264 5980-6295/de.foo.bar.baz D/SignDAO: Closing database.
03-20 17:34:25.311 5980-5980/de.foo.bar.baz D/SignSearchActivity: onCreateOptionsMenu()81236595
03-20 17:34:25.326 5980-5980/de.foo.bar.baz D/SignSearchActivity: onPostExecute 81236595
03-20 17:34:25.382 5980-5980/de.foo.bar.baz D/MainActivity: onSaveInstance
03-20 17:34:25.390 5980-5980/de.foo.bar.baz D/SignBrowserUIFragment: onSaveInstance
Orientation change will saveInstance and create a new instance of SignSearchActivity (see hashCode at the end)
03-20 17:36:21.849 5980-5980/de.foo.bar.baz D/SignSearchActivity: onPause()81236595
>> 03-20 17:36:21.849 5980-5980/de.foo.bar.baz D/SignSearchActivity: onSaveInstanceState() 81236595
03-20 17:36:21.862 5980-6039/de.foo.bar.baz E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb87d8f40
>> 03-20 17:36:21.898 5980-5980/de.foo.bar.baz D/SignSearchActivity: onCreate() 169372560
03-20 17:36:21.914 5980-5980/de.foo.bar.baz D/SignSearchActivity: setupRecyclerView() 169372560
03-20 17:36:21.914 5980-5980/de.foo.bar.baz D/SignSearchActivity: setupSupportActionBar() 169372560
03-20 17:36:21.933 5980-5980/de.foo.bar.baz D/SignSearchActivity: onStart() 169372560
03-20 17:36:21.933 5980-5980/de.foo.bar.baz D/SignSearchActivity: onPreExecute 169372560
03-20 17:36:21.939 5980-6296/de.foo.bar.baz D/SignDAO: Opening database.
03-20 17:36:21.945 5980-6296/de.foo.bar.baz I/SQLiteAssetHelper: successfully opened database signs.db
03-20 17:36:21.946 5980-6296/de.foo.bar.baz D/SignDAO: Reading signs with name_locale_de like: ma
03-20 17:36:21.947 5980-6296/de.foo.bar.baz D/SignDAO: Closing database.
03-20 17:36:21.973 5980-5980/de.foo.bar.baz D/SignSearchActivity: onCreateOptionsMenu()169372560
03-20 17:36:21.994 5980-5980/de.foo.bar.baz D/SignSearchActivity: onPostExecute 169372560
Clicking on a sign will also saveInstance
03-20 17:56:54.415 5980-5980/de.foo.bar.baz D/SignSearchActivity: onTxtSignNameClicked() 169372560
03-20 17:56:54.456 5980-5980/de.foo.bar.baz D/SignSearchActivity: onPause()169372560
03-20 17:56:54.472 5980-5980/de.foo.bar.baz D/SignSearchVideoActivity: onCreate()24174267
03-20 17:56:54.509 5980-5980/de.foo.bar.baz D/SignVideoUIFragment: onCreateView
03-20 17:56:54.644 5980-5980/de.foo.bar.baz D/SignVideoUIFragment: onActivityCreated
03-20 17:56:55.129 5980-5980/de.foo.bar.baz D/MediaPlayer: getMetadata
>> 03-20 17:56:55.182 5980-5980/de.foo.bar.baz D/SignSearchActivity: onSaveInstanceState() 169372560
03-20 17:56:55.614 5980-6001/de.foo.bar.baz W/MediaPlayer: info/warning (3, 0)
Clicking on homeAsUpIndicator will cause NullPointerException in SignSearchActitivity
03-20 18:02:40.552 1625-1625/de.foo.bar.baz D/SignSearchVideoActivity: onPause()24174267
03-20 18:02:40.635 1625-1625/de.foo.bar.baz D/SignSearchActivity: onCreate() 188070473
03-20 18:02:40.654 1625-1625/de.foo.bar.baz D/SignSearchActivity: onStart() 188070473
03-20 18:02:40.659 1625-1625/de.foo.bar.baz D/AndroidRuntime: Shutting down VM
03-20 18:02:40.672 1625-1625/de.foo.bar.baz E/AndroidRuntime: FATAL EXCEPTION: main
Process: de.foo.bar.baz, PID: 1625
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.foo.bar.baz/de.foo.bar.baz.sign_browser.search.SignSearchActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean de.foo.bar.baz.sign_browser.search.SignSearchTaskFragment.isRunning()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean de.foo.bar.baz.sign_browser.search.SignSearchTaskFragment.isRunning()' on a null object reference
at de.foo.bar.baz.sign_browser.search.SignSearchActivity.onStart(SignSearchActivity.java:91)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1260)
at android.app.Activity.performStart(Activity.java:6261)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2389)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
SignSearchActivity
package de.foo.bar.baz.sign_browser.search;
import android.app.FragmentTransaction;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
import de.foo.bar.baz.R;
import de.foo.bar.baz.database.Sign;
import de.foo.bar.baz.sign_browser.search.video.SignSearchVideoActivity;
import de.foo.bar.baz.sign_browser.video.SignVideoUIFragment;
public class SignSearchActivity extends AppCompatActivity implements SignSearchTaskFragment.TaskCallbacks {
private static final java.lang.String KEY_QUERY = "sign_browser_search_query";
private static final String TAG_TASK_FRAGMENT = "sign_browser_search_task_fragment";
private static final String TAG = SignSearchActivity.class.getSimpleName();
private SignSearchTaskFragment signSearchTaskFragment;
private String query = StringUtils.EMPTY;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate() " + this.hashCode());
super.onCreate(savedInstanceState);
setContentView(R.layout.search_activity);
if (null != savedInstanceState) {
this.query = savedInstanceState.getString(KEY_QUERY);
} else {
final Intent intent = getIntent();
if (!(Intent.ACTION_SEARCH.equals(intent.getAction()))) {
return;
}
this.query = intent.getStringExtra(SearchManager.QUERY);
}
setupRecyclerView();
setupSupportActionBar();
this.signSearchTaskFragment = (SignSearchTaskFragment) getFragmentManager().findFragmentByTag(TAG_TASK_FRAGMENT);
if (null == this.signSearchTaskFragment) {
initSignSearchTaskFragment();
}
}
private void initSignSearchTaskFragment() {
Log.d(TAG, "initSignSearchTaskFragment() " + this.hashCode());
this.signSearchTaskFragment = new SignSearchTaskFragment();
final FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.add(signSearchTaskFragment, TAG_TASK_FRAGMENT);
fragmentTransaction.commit();
}
private void setupRecyclerView() {
Log.d(TAG, "setupRecyclerView() " + this.hashCode());
final RecyclerView recyclerView = (RecyclerView) this.findViewById(R.id.signSearchRecyclerView);
// recyclerView.setHasFixedSize(true); // performance fix
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new SignSearchAdapter(new ArrayList<Sign>(), this));
}
private void setupSupportActionBar() {
Log.d(TAG, "setupSupportActionBar() " + this.hashCode());
final ActionBar supportActionBar = getSupportActionBar();
if (null == supportActionBar) {
throw new IllegalStateException("SupportActionBar is null. Should have been set in " +
"onCreate().");
}
supportActionBar.setTitle(getResources().getString(R.string.search_results) + StringUtils.SPACE + this.query);
supportActionBar.setDisplayHomeAsUpEnabled(true);
}
#Override
public void onStart() {
Log.d(TAG, "onStart() " + this.hashCode());
super.onStart();
// if (null != this.signSearchTaskFragment) {
if (!this.signSearchTaskFragment.isRunning()) {
this.signSearchTaskFragment.start(this, query);
}
// }
}
#Override
protected void onPause() {
Log.d(TAG, "onPause()" + this.hashCode());
super.onPause();
if (signSearchTaskFragment.isRunning()) {
this.signSearchTaskFragment.cancel();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.d(TAG, "onCreateOptionsMenu()" + this.hashCode());
final MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_sign_browser_search, menu);
final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
final MenuItem searchItem = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
return true;
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.d(TAG, "onSaveInstanceState() " + this.hashCode());
super.onSaveInstanceState(outState);
outState.putString(KEY_QUERY, this.query);
}
public void onTxtSignNameClicked(Sign sign) {
Log.d(TAG, "onTxtSignNameClicked() " + this.hashCode());
final Intent intent = new Intent(this, SignSearchVideoActivity.class);
final Bundle bundle = new Bundle();
bundle.putParcelable(SignVideoUIFragment.SIGN_TO_SHOW, sign);
intent.putExtra(SignSearchVideoActivity.EXTRA, bundle);
startActivity(intent);
// final Intent intent = new Intent(this, LevelOneActivity.class);
// final Bundle bundle = new Bundle();
// bundle.putString(LevelOneActivity.FRAGMENT_TO_SHOW, SignVideoUIFragment.class.getSimpleName());
// bundle.putParcelable(SignVideoUIFragment.SIGN_TO_SHOW, sign);
// intent.putExtra(LevelOneActivity.EXTRA, bundle);
// startActivity(intent);
}
#Override
public void onPreExecute() {
Log.d(TAG, "onPreExecute " + this.hashCode());
/*no-op*/
}
#Override
public void onProgressUpdate(int percent) {
Log.d(TAG, "onProgressUpdate " + this.hashCode());
/*no-op*/
}
#Override
public void onCancelled() {
Log.d(TAG, "onCancelled " + this.hashCode());
/*no-op*/
}
#Override
public void onPostExecute(List<Sign> result) {
Log.d(TAG, "onPostExecute " + this.hashCode());
// FIXME: After savedInstance has been called, this.recyclerview is null here, despite being
// FIXME: set in the onCreated() method. Therefore a findViewById is necessary.
final RecyclerView mRecyclerView = (RecyclerView) this.findViewById(R.id.signSearchRecyclerView);
if (null == mRecyclerView) {
throw new IllegalStateException("mRecyclerView is null");
}
mRecyclerView.swapAdapter(new SignSearchAdapter(result, this), false);
}
}
SignSearch_Video_Activity
package de.foo.bar.baz.sign_browser.search.video;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import org.apache.commons.lang3.StringUtils;
import de.foo.bar.baz.R;
import de.foo.bar.baz.sign_browser.video.SignVideoUIFragment;
public class SignSearchVideoActivity extends AppCompatActivity {
public static final String TAG = SignSearchVideoActivity.class.getSimpleName();
public static final String EXTRA = "extra";
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate()" + this.hashCode());
super.onCreate(savedInstanceState);
setContentView(R.layout.search_video_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (null != getSupportActionBar()) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(StringUtils.EMPTY);
}
final Intent intent = getIntent();
final Bundle bundle = intent.getBundleExtra(EXTRA);
if (null == bundle) {
throw new IllegalArgumentException("The bundle supplied to the activity is null");
}
final Parcelable sign = bundle.getParcelable(SignVideoUIFragment.SIGN_TO_SHOW);
final SignVideoUIFragment signVideoUIFragment = new SignVideoUIFragment();
final Bundle args = new Bundle();
args.putParcelable(SignVideoUIFragment.SIGN_TO_SHOW, sign);
signVideoUIFragment.setArguments(args);
final FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.searchVideoActivityContentFrame, signVideoUIFragment, "SIGN_VIDEO_TAG");
transaction.addToBackStack(null);
transaction.commit();
}
#Override
protected void onPause() {
Log.d(TAG, "onPause()" + this.hashCode());
super.onPause();
setResult(RESULT_OK);
}
}
Figured it out myself:
The problem was that even though the onCreate() method of the SignSearchActivity was executed, vital parts of it were not. This was due to the fact that the child activity did not call the SignSearchActivity (which is backing a SearchView) with the right kind of intent.
So this code
if (!(Intent.ACTION_SEARCH.equals(intent.getAction()))) {
return;
}
meant that the SignSearch.onCreate() method returned when it wasn't supposed to.
Now, the SignSearchActivity passes the query to the SignSearchVideoActivity as an intent extra. When the SignSearchVideoActivity navigates back up to the SignSearchActivity, it passes the original query back again.
Modified SignSearchActivity.onCreate() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate() " + this.hashCode());
super.onCreate(savedInstanceState);
setContentView(R.layout.search_activity);
if (null != savedInstanceState) {
this.query = savedInstanceState.getString(QUERY);
} else {
final Intent intent = getIntent();
this.query = intent.getStringExtra(SearchManager.QUERY);
Validate.notNull(this.query, "The query supplied to this activity is null!");
}
setupRecyclerView();
setupSupportActionBar();
this.signSearchTaskFragment = (SignSearchTaskFragment) getFragmentManager().findFragmentByTag(TAG_TASK_FRAGMENT);
if (null == this.signSearchTaskFragment) {
initSignSearchTaskFragment();
}
}
New SignSearchVideoActivity.onOptionItemsSelected() method.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "onOptionsItemSelected() " + this.hashCode());
switch (item.getItemId()) {
case android.R.id.home:
final Intent upIntent = NavUtils.getParentActivityIntent(this);
upIntent.putExtra(SearchManager.QUERY, this.originalQuery);
NavUtils.navigateUpTo(this, upIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
I am trying to post tweet after being authenticated with twitter4j and walking on this tutorial. The problem is that the login button doesn't do anything while it has to open authentication page. I couldn't find the reason. Thanks for help.
MainActivity:
public class MainActivity extends Activity {
// Constants
static String TWITTER_CONSUMER_KEY = "my_api_key";
static String TWITTER_CONSUMER_SECRET = "my_api_secret";
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
// Login button
Button btnLoginTwitter;
// Update status button
Button btnUpdateStatus;
// Logout button
Button btnLogoutTwitter;
// EditText for update
EditText txtUpdate;
// lbl update
TextView lblUpdate;
TextView lblUserName;
// Progress dialog
ProgressDialog pDialog;
// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if twitter keys are set
if(TWITTER_CONSUMER_KEY.trim().length() == 0 || TWITTER_CONSUMER_SECRET.trim().length() == 0){
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this, "Twitter oAuth tokens", "Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
// All UI elements
btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
btnUpdateStatus = (Button) findViewById(R.id.btnUpdateStatus);
btnLogoutTwitter = (Button) findViewById(R.id.btnLogoutTwitter);
txtUpdate = (EditText) findViewById(R.id.txtUpdateStatus);
lblUpdate = (TextView) findViewById(R.id.lblUpdate);
lblUserName = (TextView) findViewById(R.id.lblUserName);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
/**
* Twitter login button click event will call loginToTwitter() function
* */
btnLoginTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call login twitter function
loginToTwitter();
}
});
/**
* Button click event to Update Status, will call updateTwitterStatus()
* function
* */
btnUpdateStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Call update status function
// Get the status from EditText
String status = txtUpdate.getText().toString();
// Check for blank text
if (status.trim().length() > 0) {
// update status
new updateTwitterStatus().execute(status);
} else {
// EditText is empty
Toast.makeText(getApplicationContext(),
"Please enter status message", Toast.LENGTH_SHORT)
.show();
}
}
});
/**
* Button click event for logout from twitter
* */
btnLogoutTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Call logout twitter function
logoutFromTwitter();
}
});
/** This if conditions is tested once is
* redirected from twitter page. Parse the uri to get oAuth
* Verifier
* */
if (!isTwitterLoggedInAlready()) {
Uri uri = getIntent().getData();
if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {
// oAuth verifier
String verifier = uri
.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
// Get the access token
AccessToken accessToken = twitter.getOAuthAccessToken(
requestToken, verifier);
// Shared Preferences
Editor e = mSharedPreferences.edit();
// After getting access token, access token secret
// store them in application preferences
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET,
accessToken.getTokenSecret());
// Store login status - true
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.commit(); // save changes
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
// Hide login button
btnLoginTwitter.setVisibility(View.GONE);
// Show Update Twitter
lblUpdate.setVisibility(View.VISIBLE);
txtUpdate.setVisibility(View.VISIBLE);
btnUpdateStatus.setVisibility(View.VISIBLE);
btnLogoutTwitter.setVisibility(View.VISIBLE);
// Getting user details from twitter
// For now i am getting his name only
long userID = accessToken.getUserId();
User user = twitter.showUser(userID);
String username = user.getName();
// Displaying in xml ui
lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>"));
} catch (Exception e) {
// Check log for login errors
Log.e("Twitter Login Error", "> " + e.getMessage());
}
}
}
}
/**
* Function to login twitter
* */
private void loginToTwitter() {
// Check if already logged in
if (!isTwitterLoggedInAlready()) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter
.getOAuthRequestToken(TWITTER_CALLBACK_URL);
this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
} else {
// user already logged into twitter
Toast.makeText(getApplicationContext(),
"Already Logged into twitter", Toast.LENGTH_LONG).show();
}
}
/**
* Function to update status
* */
class updateTwitterStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access Token
String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// Update status
twitter4j.Status response = twitter.updateStatus(status);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
/**
* After completing background task Dismiss the progress dialog and show
* the data in UI Always use runOnUiThread(new Runnable()) to update UI
* from background thread, otherwise you will get error
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
// Clearing EditText field
txtUpdate.setText("");
}
});
}
}
/**
* Function to logout from twitter
* It will just clear the application shared preferences
* */
private void logoutFromTwitter() {
// Clear the shared preferences
Editor e = mSharedPreferences.edit();
e.remove(PREF_KEY_OAUTH_TOKEN);
e.remove(PREF_KEY_OAUTH_SECRET);
e.remove(PREF_KEY_TWITTER_LOGIN);
e.commit();
// After this take the appropriate action
// I am showing the hiding/showing buttons again
// You might not needed this code
btnLogoutTwitter.setVisibility(View.GONE);
btnUpdateStatus.setVisibility(View.GONE);
txtUpdate.setVisibility(View.GONE);
lblUpdate.setVisibility(View.GONE);
lblUserName.setText("");
lblUserName.setVisibility(View.GONE);
btnLoginTwitter.setVisibility(View.VISIBLE);
}
/**
* Check user already logged in your application using twitter Login flag is
* fetched from Shared Preferences
* */
private boolean isTwitterLoggedInAlready() {
// return twitter login status from Shared Preferences
return mSharedPreferences.getBoolean(PREF_KEY_TWITTER_LOGIN, false);
}
protected void onResume() {
super.onResume();
}
}
Error Log:
03-20 12:12:56.779: E/AudioMTKHardware(8976): setParameters() still have param.size() = 1, remain param = "screen_state=off"
03-20 12:13:01.714: E/Looper(494): WARNING: The Looper class instance count has over a limit(100). There should be some leakage of Looper or HandlerThread.
03-20 12:13:01.715: E/Looper(494): Looper class instance count = 113
03-20 12:13:01.715: E/Looper(494): Current Thread Name: KeyguardWidgetPager Worker
03-20 12:13:05.991: E/stp_dump(147): table == NULL || table->table == NULL
03-20 12:13:05.991: E/stp_dump(147): table == NULL || table->table == NULL
03-20 12:13:05.997: E/CellLocation(976): create GsmCellLocation
03-20 12:13:06.014: E/CellLocation(976): create GsmCellLocation
03-20 12:13:06.468: E/wpa_supplicant(29010): Sorted scan results
03-20 12:13:06.468: E/wpa_supplicant(29010): 28:10:7b:94:c5:79 freq=2437 qual=0 noise=0 level=-78 flags=0x2b
03-20 12:13:06.468: E/wpa_supplicant(29010): IEs
03-20 12:13:06.468: E/wpa_supplicant(29010): 000854454e454b454349010882848b962430486c0301062a01042f010430140100000fac040100000fac040100000fac020c0032040c1218602d1a6c181bff000000000000000000000000000000000000000000003d1606000000000000000000000000000000000000000000dd7b0050f204104a00011010440001021041000100103b0001031047001076c42cdafbfc3780d3ea25f0dc470d6f1021000842726f6164636f6d1023000842726f6164636f6d1024000631323334353610420004313233341054000800060050f20400011011000a42726f6164636f6d4150100800020084103c000101dd090010180201f0040000dd180050f2020101800003a4000027a4000042435e0062322f00
03-20 12:13:06.468: E/wpa_supplicant(29010): Beacon IEs
03-20 12:13:06.468: E/wpa_supplicant(29010): 000854454e454b454349010882848b962430486c0301060504000100002a01002f010030140100000fac040100000fac040100000fac020c0032040c1218602d1a6c181bff000000000000000000000000000000000000000000003d1606000000000000000000000000000000000000000000dd0e0050f204104a0001101044000102dd090010180200f0040000dd180050f2020101800003a4000027a4000042435e0062322f00
03-20 12:13:06.468: E/wpa_supplicant(29010): f8:1a:67:b8:c4:be freq=2457 qual=0 noise=0 level=-87 flags=0xb
03-20 12:13:06.468: E/wpa_supplicant(29010): IEs
03-20 12:13:06.468: E/wpa_supplicant(29010): 001154544e45545f54504c494e4b5f43344245010882848b960c12182403010a2a010032043048606c2d1a6e181effff0000000000000000000000000000000000000000003d160a0000000000000000000000000000000000000000004a0e14000a00b400c8001400050019007f0101dd1a0050f20101000050f20202000050f2020050f20401000050f20230180100000fac020200000fac02000fac040100000fac020000dd180050f2020101000003a4000027a4000042435e0062322f00dd1e00904c336e181effff000000000000000000000000000000000000000000dd1a00904c340a000000000000000000000000000000000000000000dd0600e04c020160dda40050f204104a0001101044000102103b0001031047001063041253101920061228f81a67b8c4be1021001b5265616c74656b2053656d69636f6e647563746f7220436f72702e1023000752544c383637311024000d45562d323030362d30372d32371042000f3132333435363738393031323334371054000800060050f20400011011000f54502d4c494e4b2050726f647563741008000200061049000600372a000120
03-20 12:13:06.468: E/wpa_supplicant(29010): Beacon IEs
03-20 12:13:06.468: E/wpa_supplicant(29010): 001154544e45545f54504c494e4b5f43344245010882848b960c12182403010a0504000101002a010432043048606c2d1a6e181effff0000000000000000000000000000000000000000003d160a0000000000000000000000000000000000000000004a0e14000a00b400c8001400050019007f0101dd1a0050f20101000050f20202000050f2020050f20401000050f20230180100000fac020200000fac02000fac040100000fac020000dd180050f2020101000003a4000027a4000042435e0062322f00dd1e00904c336e181effff000000000000000000000000000000000000000000dd1a00904c340a000000000000000000000000000000000000000000dd0600e04c020160dd180050f204104a00011010440001021049000600372a000120
03-20 12:13:06.468: E/wpa_supplicant(29010): 64:66:b3:ed:de:26 freq=2472 qual=0 noise=0 level=-90 flags=0xb
03-20 12:13:06.468: E/wpa_supplicant(29010): IEs
03-20 12:13:06.469: E/stp_dump(147): table == NULL || table->table == NULL
03-20 12:13:06.469: E/stp_dump(147): table == NULL || table->table == NULL
03-20 12:13:06.470: E/wpa_supplicant(29010): 00074d757a65203335010882848b961224486c03010d2a010432040c1830602d1a6e1117ff000000010000000000000000000000000c00000000003d160d0700000000000000000000000000000000000000003e010030180100000fac020200000fac02000fac040100000fac020000dd180050f2020101000003a4000027a4000042435e0062322f004a0e14000a002c01c800140005001900dd07000c43040000000706545200010d10dd9d0050f204104a0001001044000102103b00010310470010bc329e001dd811b286016466b3edde261021001852616c696e6b20546563686e6f6c6f67792c20436f72702e1023001c52616c696e6b20576972656c6573732041636365737320506f696e74102400065254323836301042000831323334353637381054000800060050f20400011011000952616c696e6b415053100800020004103c000100
03-20 12:13:06.470: E/wpa_supplicant(29010): Beacon IEs
03-20 12:13:06.471: E/wpa_supplicant(29010): 00074d757a65203335010882848b961224486c03010d32040c1830600706545200010d143308200102030405060733082105060708090a0b050400010000dd270050f204104a000100104400010210470010bc329e001dd811b286016466b3edde26103c0001012a01042d1a6e1117ff000000010000000000000000000000000c00000000003d160d0700000000000000000000000000000000000000004a0e14000a002c01c80014000500190030180100000fac020200000fac02000fac040100000fac020000dd180050f2020101000003a4000027a4000042435e0062322f00dd07000c4304000000
03-20 12:13:06.483: E/wpa_supplicant(29010): WPS: WFA subelement id=0 len=1
03-20 12:13:06.483: E/wpa_supplicant(29010): WPS: WFA subelement id=0 len=1
03-20 12:13:06.483: E/wpa_supplicant(29010): WPS: WFA subelement id=0 len=1
03-20 12:14:06.019: E/stp_dump(147): table == NULL || table->table == NULL
03-20 12:14:06.019: E/stp_dump(147): table == NULL || table->table == NULL
03-20 12:14:06.026: E/CellLocation(976): create GsmCellLocation
03-20 12:14:06.042: E/CellLocation(976): create GsmCellLocation
03-20 12:14:06.506: E/wpa_supplicant(29010): Sorted scan results
03-20 12:14:06.506: E/wpa_supplicant(29010): 28:10:7b:94:c5:79 freq=2437 qual=0 noise=0 level=-84 flags=0x2b
03-20 12:14:06.506: E/wpa_supplicant(29010): IEs
03-20 12:14:06.506: E/wpa_supplicant(29010): 000854454e454b454349010882848b962430486c0301062a01042f010430140100000fac040100000fac040100000fac020c0032040c1218602d1a6c181bff000000000000000000000000000000000000000000003d1606000000000000000000000000000000000000000000dd7b0050f204104a00011010440001021041000100103b0001031047001076c42cdafbfc3780d3ea25f0dc470d6f1021000842726f6164636f6d1023000842726f6164636f6d1024000631323334353610420004313233341054000800060050f20400011011000a42726f6164636f6d4150100800020084103c000101dd090010180201f0040000dd180050f2020101800003a4000027a4000042435e0062322f00
03-20 12:14:06.506: E/wpa_supplicant(29010): Beacon IEs
03-20 12:14:06.506: E/wpa_supplicant(29010): 000854454e454b454349010882848b962430486c0301060504000100002a01002f010030140100000fac040100000fac040100000fac020c0032040c1218602d1a6c181bff000000000000000000000000000000000000000000003d1606000000000000000000000000000000000000000000dd0e0050f204104a0001101044000102dd090010180200f0040000dd180050f2020101800003a4000027a4000042435e0062322f00
03-20 12:14:06.506: E/wpa_supplicant(29010): 64:66:b3:ed:de:26 freq=2472 qual=0 noise=0 level=-89 flags=0xb
03-20 12:14:06.506: E/wpa_supplicant(29010): IEs
03-20 12:14:06.506: E/wpa_supplicant(29010): 00074d757a65203335010882848b961224486c03010d2a010432040c1830602d1a6e1117ff000000010000000000000000000000000c00000000003d160d0700000000000000000000000000000000000000003e010030180100000fac020200000fac02000fac040100000fac020000dd180050f2020101000003a4000027a4000042435e0062322f004a0e14000a002c01c800140005001900dd07000c43040000000706545200010d10dd9d0050f204104a0001001044000102103b00010310470010bc329e001dd811b286016466b3edde261021001852616c696e6b20546563686e6f6c6f67792c20436f72702e1023001c52616c696e6b20576972656c6573732041636365737320506f696e74102400065254323836301042000831323334353637381054000800060050f20400011011000952616c696e6b415053100800020004103c000100
03-20 12:14:06.506: E/wpa_supplicant(29010): Beacon IEs
03-20 12:14:06.506: E/wpa_supplicant(29010): 00074d757a65203335010882848b961224486c03010d32040c1830600706545200010d143308200102030405060733082105060708090a0b050400010000dd270050f204104a000100104400010210470010bc329e001dd811b286016466b3edde26103c0001012a01042d1a6e1117ff000000010000000000000000000000000c00000000003d160d0700000000000000000000000000000000000000004a0e14000a002c01c80014000500190030180100000fac020200000fac02000fac040100000fac020000dd180050f2020101000003a4000027a4000042435e0062322f00dd07000c4304000000
03-20 12:14:06.506: E/wpa_supplicant(29010): 00:27:22:82:e8:21 freq=2437 qual=0 noise=0 level=-93 flags=0xb
03-20 12:14:06.506: E/wpa_supplicant(29010): IEs
03-20 12:14:06.507: E/wpa_supplicant(29010): 00066b6174322d31010882848b960c1218240301060504000100002a0100dd26000c42000000011e000000001f660902ff0f55424e540000000000000000000000000000000032043048606cdd180050f202010182000364000027a4000041435e0061322f00dd1e00904c334c101bffff0000000000000000000000000000000000000000002d1a4c101bffff000000000000000000000000000000000000000000dd1a00904c3406001b000000000000000000000000000000000000003d1606001b00000000000000000000000000000000000000dd0900037f01010000ff7fdd0a00037f04010002004000dd0e00156d000000010212e002021200
03-20 12:14:06.507: E/stp_dump(147): table == NULL || table->table == NULL
03-20 12:14:06.507: E/stp_dump(147): table == NULL || table->table == NULL
03-20 12:14:06.518: E/wpa_supplicant(29010): WPS: WFA subelement id=0 len=1
03-20 12:14:06.518: E/wpa_supplicant(29010): WPS: WFA subelement id=0 len=1
03-20 12:14:06.518: E/wpa_supplicant(29010): WPS: WFA subelement id=0 len=1
EDIT:
After updated the jar file to last version (Twitter4j 4.0.1) there is no more log errors but only warnings and button still doesn't work. Here is new error log.
android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#406a6678 is not valid; is your activity running?
at android.view.ViewRoot.setView(ViewRoot.java:528)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.view.Window$LocalWindowManager.addView(Window.java:424)
at android.app.Dialog.show(Dialog.java:241)
at android.app.Activity.showDialog(Activity.java:2569)
at android.app.Activity.showDialog(Activity.java:2527)
at MyCode$8$4.run(MyCode.java:557)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
at dalvik.system.NativeStart.main(Native Method)
I am getting above exception when following code is executed. This file dialog will shown once the processing is done and progressbar reaches 100%. FileSaveDialog extends Dialog and implements OnCompletionListener
runOnUiThread(new Runnable() {
#Override
public void run() {
showDialog(error.Code());//Line 557
}
});
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog;
AlertDialog.Builder builder;
final ScrollView scrollView = new ScrollView(this);
final TextView textView = new TextView(this);
switch (id) {
// Other cases are here
case 4:
File playFile = new File(mediaPath, TEMP_WAV_FILE_NAME);
dialog = new FileSaveDialog(this, getResources(),
playFile.getAbsolutePath(), saveDiscardHandler);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// do whatever you want the back key to do
cleanUp();
}
});
break;
// Other cases are here
default:
dialog = null;
}
return dialog;
}
You must check activity isFinishing() If the activity is finishing, returns true; else returns false.
the activity crashes when I try and set any imageview image (either setImageBitmap or setImageView) it does this anywhere but in the one getview.
I am trying to get an imageview array that I can use in my adapter for my gridview (problem marked "problem here")
package joshpike.hsh.hsh_game;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class DisplayActivity extends MainActivity
{
int screenTileWidth = 3;
int nativeTileSize = 256;
int tileSize;
int numberColumn;
int numberRow;
int floorNum;
ImageView[][] topGridArray = null;
ImageView[][] bottomGridArray = null;
//sets tilesize, numberColumn and numberRow
#SuppressLint("NewApi")
public void setGridVars()
{
//set tileSize
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
int screenWidth;
if (android.os.Build.VERSION.SDK_INT >= 13)
{
display.getSize(size);
screenWidth = size.x;
}
else
{
screenWidth = display.getWidth();
}
tileSize = screenWidth / screenTileWidth;
//set numberColumn and numberRow
try
{
String dataFilePath = "floors/" + floorNum + "/FloorData.txt";
InputStream dataInputStream = getAssets().open(dataFilePath);
BufferedReader reader = new BufferedReader(new InputStreamReader(dataInputStream));
String line = reader.readLine();
line = reader.readLine();
numberColumn = Integer.parseInt(line);
line = reader.readLine();
numberRow = Integer.parseInt(line);
dataInputStream.close();
}
catch (IOException e)
{
System.out.println("exception found in try/catch in DisplayActivity.setGridVars method");
}
for(int x = 0; x < numberColumn ; x++ )
{
for(int y = 0; y < numberRow ; y++ )
{
///***PROBLEM HERE***///
bottomGridArray[x][y].setImageBitmap(currentImageView("bottom", x, y));
topGridArray[x][y].setImageBitmap(currentImageView("top", x, y));
}
}
}
//returns the one imageView for gridViewForadapter
public Bitmap currentImageView(String layer, int X, int Y )
{
try
{
Bitmap returnBitmap = null;
String imgDirectory = "floors/" + floorNum + "/" + layer + "/" + X + "," + Y + ".png";
InputStream imageInputStream = getAssets().open(imgDirectory);
returnBitmap = BitmapFactory.decodeStream(imageInputStream);
imageInputStream.close();
return returnBitmap;
}
catch (IOException e)
{
System.out.println("exception found in try/catch in DisplayActivity.currentImageView method");
return null;
}
}
public int returnGridCord (int position, char whatCord)
{
position = position + 1;
float rowFromTop = (float) position / numberColumn;
if (rowFromTop != Math.round(rowFromTop))
{
rowFromTop = ((float) Math.ceil( rowFromTop));
}
int returnY = Math.abs( (int)rowFromTop - numberRow);
int returnX = (position - ( ( (int)rowFromTop -1 ) * numberColumn) ) - 1;
System.out.println(position + ":" + returnX + "x" + returnY);
if (whatCord == 'X')
{
return returnX;
}
else
{
return returnY;
}
}
public class ImageAdapter extends BaseAdapter
{
private Context mContext;
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
if (convertView == null)
{
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(tileSize, tileSize));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(0, 0, 0, 0);
}
else
{
imageView = (ImageView) convertView;
}
System.out.println("endish of getview");
imageView.setImageResource(R.drawable.ic_launcher);
return imageView;
}
public ImageAdapter(Context c)
{
mContext = c;
}
#Override
public int getCount()
{
return numberColumn * numberRow;
}
#Override
public Object getItem(int position)
{
return null;
}
#Override
public long getItemId(int position)
{
return 0;
}
}
// Inflate the menu; this adds items to the action bar if it is present.
//makes the options menu
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.display, menu);
return true;
}
//what happens if you select items from the options menu
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId() )
{
case R.id.miniMap:
return true;
}
return super.onOptionsItemSelected(item);
}
//called when activity is started for first time either for first time or after destoryed
#Override
protected void onCreate(Bundle savedInstanceState)
{
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
setGridVars();
System.out.println("DisplayActivity test about to start");
//ImageAdapter test = null;
//returnGridCord(0,"X");
GridView bottomMapGrid = (GridView)findViewById(R.id.bottomMapGrid);
bottomMapGrid.setNumColumns(numberColumn);
bottomMapGrid.setColumnWidth( tileSize );
bottomMapGrid.setStretchMode( GridView.NO_STRETCH ) ;
bottomMapGrid.setAdapter(new ImageAdapter(this));
System.out.println("DisplayActivity onCreate done");
}
//called when Activity goes from paused to active
#Override
protected void onResume()
{
super.onResume();
System.out.println("DisplayActivity onResume done");
}
//called when Activity goes from active to paused
#Override
protected void onPause()
{
super.onPause();
System.out.println("DisplayActivity onPause done");
}
//called when Activity goes from paused to stopped
#Override
protected void onStop()
{
super.onStop();
System.out.println("DisplayActivity onStop done");
}
//called when Activity goes from stopped to destroyed
#Override
protected void onDestroy()
{
super.onDestroy();
System.out.println("DisplayActivity onDestroy done");
}
//called when Activity has been stopped, is going to be paused then active
#Override
protected void onRestart()
{
super.onRestart();
System.out.println("DisplayActivity onRestart done");
}
//called when Activity is transitioning to paused either for first time or after it has been stopped
#Override
protected void onStart()
{
super.onStart();
System.out.println("DisplayActivity onStart done");
}
}
logcat:
03-20 17:16:43.437: I/System.out(22850): MainActivity onCreate done
03-20 17:16:43.437: I/System.out(22850): MainActivity onStart done
03-20 17:16:43.437: I/System.out(22850): MainActivity onResume done
03-20 17:16:43.848: D/TextLayoutCache(22850): Using debug level: 0 - Debug Enabled: 0
03-20 17:16:44.088: D/libEGL(22850): loaded /system/lib/egl/libGLES_android.so
03-20 17:16:44.168: D/libEGL(22850): loaded /system/lib/egl/libEGL_mali.so
03-20 17:16:44.208: D/libEGL(22850): loaded /system/lib/egl/libGLESv1_CM_mali.so
03-20 17:16:44.218: D/libEGL(22850): loaded /system/lib/egl/libGLESv2_mali.so
03-20 17:16:44.358: D/OpenGLRenderer(22850): Enabling debug mode 0
03-20 17:16:48.973: I/System.out(22850): MainActivity onPause done
03-20 17:16:49.974: D/OpenGLRenderer(22850): Flushing caches (mode 0)
03-20 17:16:50.674: I/System.out(22850): MainActivity onCreate done
03-20 17:16:50.915: D/AndroidRuntime(22850): Shutting down VM
03-20 17:16:50.915: W/dalvikvm(22850): threadid=1: thread exiting with uncaught exception (group=0x40aa8210)
03-20 17:16:51.005: E/AndroidRuntime(22850): FATAL EXCEPTION: main
03-20 17:16:51.005: E/AndroidRuntime(22850): java.lang.RuntimeException: Unable to start activity ComponentInfo{joshpike.hsh.hsh_game/joshpike.hsh.hsh_game.DisplayActivity}: java.lang.NullPointerException
03-20 17:16:51.005: E/AndroidRuntime(22850): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1967)
03-20 17:16:51.005: E/AndroidRuntime(22850): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
03-20 17:16:51.005: E/AndroidRuntime(22850): at android.app.ActivityThread.access$600(ActivityThread.java:127)
03-20 17:16:51.005: E/AndroidRuntime(22850): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
03-20 17:16:51.005: E/AndroidRuntime(22850): at android.os.Handler.dispatchMessage(Handler.java:99)
03-20 17:16:51.005: E/AndroidRuntime(22850): at android.os.Looper.loop(Looper.java:137)
03-20 17:16:51.005: E/AndroidRuntime(22850): at android.app.ActivityThread.main(ActivityThread.java:4448)
03-20 17:16:51.005: E/AndroidRuntime(22850): at java.lang.reflect.Method.invokeNative(Native Method)
03-20 17:16:51.005: E/AndroidRuntime(22850): at java.lang.reflect.Method.invoke(Method.java:511)
03-20 17:16:51.005: E/AndroidRuntime(22850): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
03-20 17:16:51.005: E/AndroidRuntime(22850): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
03-20 17:16:51.005: E/AndroidRuntime(22850): at dalvik.system.NativeStart.main(Native Method)
03-20 17:16:51.005: E/AndroidRuntime(22850): Caused by: java.lang.NullPointerException
03-20 17:16:51.005: E/AndroidRuntime(22850): at joshpike.hsh.hsh_game.DisplayActivity.setGridVars(DisplayActivity.java:85)
03-20 17:16:51.005: E/AndroidRuntime(22850): at joshpike.hsh.hsh_game.DisplayActivity.onCreate(DisplayActivity.java:235)
03-20 17:16:51.005: E/AndroidRuntime(22850): at android.app.Activity.performCreate(Activity.java:4465)
03-20 17:16:51.005: E/AndroidRuntime(22850): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
03-20 17:16:51.005: E/AndroidRuntime(22850): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1931)
03-20 17:16:51.005: E/AndroidRuntime(22850): ... 11 more
03-20 17:16:56.510: I/Process(22850): Sending signal. PID: 22850 SIG: 9
You never initialize bottomGridArray. Nor topGridArray , for that matter. (Look at this topic in a basic Java tutorial to see how and why you need to initialize your arrays)
Before your line
for(int x = 0; x < numberColumn ; x++ )
{
for(int y = 0; y < numberRow ; y++ )
insert
bottomGridArray = new ImageGrid[numberColumn][numberRow];
topGridArray = new ImageGrid[numberColumn][numberRow];
Mind you: Your code probably will have a lot of trouble. You probably should take a look at Google's recommendations for Bitmaps in your UI.