Bitmap returns null when taking screenshot - java

I'm trying to get a screenshot from a fragment, but seems that when I do
bitmap = view.getDrawingCache(); it returns null. Does anyone knows why is this happening and how can I fix this?
here is my code:
public void takeScreenshot(View view) {
OutputStream output;
view = view.getRootView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache(true);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath + "/"
+ getString(R.string.app_name) + "/");
dir.mkdirs();
File file = new File(dir, getString(R.string.app_name) + ".jpg");
bitmap = view.getDrawingCache();
try {
output = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, output);
output.flush();
output.close();
Log.d(TAG, "screenshot saved");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
and calling the method
takeScreenshot(getActivity().findViewById(R.id.fragment_container));
and here is the logCat output:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.contractfit/com.contractfit.activities.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
at android.app.ActivityThread.access$900(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5602)
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:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.contractfit.fragments.BaseFragment.takeScreenshot(BaseFragment.java:532)
at com.contractfit.fragments.MainFragment.init(MainFragment.java:211)
at com.contractfit.fragments.MainFragment.onCreateView(MainFragment.java:116)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:551)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1177)
at android.app.Activity.performStart(Activity.java:5461)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2386)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
            at android.app.ActivityThread.access$900(ActivityThread.java:175)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5602)
            at java.lang.reflect.Method.invokeNative(Native Method)

Consider doing this like Instrumentation test cases do it, your code is close but differs a bit.
From https://android.googlesource.com/platform/external/droiddriver/+/367267b/src/io/appium/droiddriver/instrumentation/InstrumentationUiDevice.java
Get root view (if it's public):
context.getDriver().getRootElement().getRawElement()));
Take screenshot
public Bitmap call() {
Bitmap screenshot;
rootView.destroyDrawingCache();
rootView.buildDrawingCache(false);
Bitmap drawingCache = rootView.getDrawingCache();
int[] xy = new int[2];
rootView.getLocationOnScreen(xy);
if (xy[0] == 0 && xy[1] == 0) {
screenshot = Bitmap.createBitmap(drawingCache);
} else {
Canvas canvas = new Canvas();
Rect rect = new Rect(0, 0, drawingCache.getWidth(), drawingCache.getHeight());
rect.offset(xy[0], xy[1]);
screenshot =
Bitmap.createBitmap(rect.width() + xy[0], rect.height() + xy[1], Config.ARGB_8888);
canvas.setBitmap(screenshot);
canvas.drawBitmap(drawingCache, null, new RectF(rect), null);
canvas.setBitmap(null);
}
rootView.destroyDrawingCache();
return screenshot;

Related

My Preferencescreen is not working on a real device

In my app the user can open the settings menu (which is a PreferenceActivity) by pressing a button. This works fine on the AVD, but when I try to use it on a real device it doesn't work. I don't know how this happened and I hope someone can help me.
Here is my PreferenceActivity:
public class ActivityPref extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref);
Preference preferences=findPreference("key");
preferences.setIntent(new Intent(this, PwdChange.class));
showNoti();
checkForBackUp();
}
private void checkForBackUp() {
final CheckBoxPreference cb = (CheckBoxPreference) getPreferenceManager().findPreference("backUp");
cb.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
if(preference.isEnabled()){
final String inFileName = "/data/data/com.sus.pwd/databases/my_d";
String outFileName = Environment.getExternalStorageDirectory()+"/database_copy.db";
OutputStream output = null;
FileInputStream fis=null;
File dbFile = new File(inFileName);
try {
fis = new FileInputStream(dbFile);
output = new FileOutputStream(outFileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
try {
while ((length = fis.read(buffer))>0){
try {
output.write(buffer, 0, length);
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
try {
output.flush();
output.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
});
}
private void showNoti() {
final CheckBoxPreference cb = (CheckBoxPreference) getPreferenceManager().findPreference("key1");
cb.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean myValue = (Boolean) newValue;
if (newValue.toString().equals("true")) {
Context context = getApplicationContext();
Toast.makeText(context, "start..", Toast.LENGTH_SHORT).show();
Log.e("value", String.valueOf(myValue));
NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.delete);
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 1, intent, 0);
builder.setContentIntent(pIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notif = builder.build();
mNotificationManager.notify(1, notif);
} else if (newValue.toString().equals("false")) {
Toast.makeText(getApplicationContext(), "stop..", Toast.LENGTH_SHORT).show();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(1);
}
return true;
}
});
}
}
Here is my main activity:
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id==R.id.settings){
startActivity(new Intent(this, ActivityPref.class));
}
}
And here is the LogCat:
05-20 17:28:19.476 11771-11771/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sushanta.reminderpwd, PID: 11771
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sushanta.reminderpwd/com.sushanta.reminderpwd.ActivityPref}: android.view.InflateException: Binary XML file line #41: Error inflating class java.lang.reflect.Constructor
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2338)
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:1321)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
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:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #41: Error inflating class java.lang.reflect.Constructor
at android.preference.GenericInflater.createItem(GenericInflater.java:397)
at android.preference.GenericInflater.onCreateItem(GenericInflater.java:417)
at android.preference.GenericInflater.createItemFromTag(GenericInflater.java:428)
at android.preference.GenericInflater.rInflate(GenericInflater.java:481)
at android.preference.GenericInflater.rInflate(GenericInflater.java:493)
at android.preference.GenericInflater.inflate(GenericInflater.java:326)
at android.preference.GenericInflater.inflate(GenericInflater.java:263)
at android.preference.PreferenceManager.inflateFromResource(PreferenceManager.java:276)
at android.preference.PreferenceActivity.addPreferencesFromResource(PreferenceActivity.java:1512)
at com.sushanta.reminderpwd.ActivityPref.onCreate(ActivityPref.java:29)
at android.app.Activity.performCreate(Activity.java:5264)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302)
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:1321) 
at android.os.Handler.dispatchMessage(Handler.java:110) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:5292) 
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:824) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at android.preference.GenericInflater.createItem(GenericInflater.java:383)
at android.preference.GenericInflater.onCreateItem(GenericInflater.java:417) 
at android.preference.GenericInflater.createItemFromTag(GenericInflater.java:428) 
at android.preference.GenericInflater.rInflate(GenericInflater.java:481) 
at android.preference.GenericInflater.rInflate(GenericInflater.java:493) 
at android.preference.GenericInflater.inflate(GenericInflater.java:326) 
at android.preference.GenericInflater.inflate(GenericInflater.java:263) 
at android.preference.PreferenceManager.inflateFromResource(PreferenceManager.java:276) 
at android.preference.PreferenceActivity.addPreferencesFromResource(PreferenceActivity.java:1512) 
at com.sushanta.reminderpwd.ActivityPref.onCreate(ActivityPref.java:29) 
at android.app.Activity.performCreate(Activity.java:5264) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302) 
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:1321) 
at android.os.Handler.dispatchMessage(Handler.java:110) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:5292) 
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:824) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.NullPointerException
at android.content.res.AssetManager.getResourceTextArray(AssetManager.java:228)
at android.content.res.Resources.getTextArray(Resources.java:458)
at android.content.res.TypedArray.getTextArray(TypedArray.java:629)
at android.preference.ListPreference.<init>(ListPreference.java:51)
at java.lang.reflect.Constructor.constructNative(Native Method) 
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) 
at android.preference.GenericInflater.createItem(GenericInflater.java:383) 
at android.preference.GenericInflater.onCreateItem(GenericInflater.java:417) 
at android.preference.GenericInflater.createItemFromTag(GenericInflater.java:428) 
at android.preference.GenericInflater.rInflate(GenericInflater.java:481) 
at android.preference.GenericInflater.rInflate(GenericInflater.java:493) 
at android.preference.GenericInflater.inflate(GenericInflater.java:326) 
at android.preference.GenericInflater.inflate(GenericInflater.java:263) 
at android.preference.PreferenceManager.inflateFromResource(PreferenceManager.java:276) 
at android.preference.PreferenceActivity.addPreferencesFromResource(PreferenceActivity.java:1512) 
at com.sushanta.reminderpwd.ActivityPref.onCreate(ActivityPref.java:29) 
at android.app.Activity.performCreate(Activity.java:5264) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302) 
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:1321) 
at android.os.Handler.dispatchMessage(Handler.java:110) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:5292) 
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:824) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640) 
at dalvik.system.NativeStart.main(Native Method) 
05-20 17:28:21.049 25577-25577/? E/NotificationService: unable to notify listener (removed): android.service.notification.INotificationListener$Stub$Proxy#428150b0
android.os.DeadObjectException
at android.os.BinderProxy.transact(Native Method)
at android.service.notification.INotificationListener$Stub$Proxy.onNotificationRemoved(INotificationListener.java:120)
at com.android.server.NotificationManagerService$NotificationListenerInfo.notifyRemovedIfUserMatch(NotificationManagerService.java:273)
at com.android.server.NotificationManagerService$3.run(NotificationManagerService.java:854)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at com.android.server.ServerThread.initAndLoop(SystemServer.java:1452)
at com.android.server.SystemServer.main(SystemServer.java:1547)
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:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
//pref.xml
<Preference
android:title="Change Master password"
android:key="key"/>
<CheckBoxPreference
android:title="Notification on Action Bar"
android:key="key1"
android:defaultValue="true"/>
<CheckBoxPreference
android:title="Back up"
android:key="backUp"
android:summary="Load data to external device"
android:defaultValue="false"/>
<CheckBoxPreference
android:title="Auto Exit"
android:summary="The Application will automatically exit when the screen turns off"
android:defaultValue="true"/>

Java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
So I am coding a translation app and this error is persisting.
Here is the code, PLEASE help!
RAW CODE 1
public class MyActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.MESSAGE"; //Defining EXTRA MESSAGE
public static Boolean hisCheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
ToggleButton toggle = (ToggleButton) findViewById(R.id.his);
}
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
if(isChecked){
hisCheck = true;
}
else {
hisCheck = false;
}
}
public void sendMessage(View view){
Intent intent = new Intent("com.robertb.TRANSLATED");
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
RAW CODE 2
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String input = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);
Set<String> output = new HashSet<String>();
String[] outputS = new String[500];
Boolean check = MyActivity.hisCheck;
// output[0] = "There are no detected gender specific words within your submitted message";
int j = 0;
String outputFinal;;
List<String> lines = new ArrayList<String>();
List<String> lines2 = new ArrayList<String>();
AssetManager assetManager = getAssets();
//goodwords array
try {
InputStream goodIs = null;
if(check){
goodIs = assetManager.open("goodwords.txt");
}
if(check){
goodIs = assetManager.open("goodwordshis.txt");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(goodIs));
String line;
while ((line = reader.readLine()) != null) {
lines2.add(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//badwords array
try {
InputStream badIs = null;
if(!check){
badIs = assetManager.open("badwords.txt");
}if(check){
badIs = assetManager.open("badwordshis.txt");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(badIs));
String line1;
while ((line1 = reader.readLine()) != null) {
lines.add(line1);
}
String[] arrayBad = lines.toArray(new String[0]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String[] arrayGood = lines2.toArray(new String[0]);
String[] arrayBad = lines.toArray(new String[0]);
String[] words = input.split("\\W");
for(int i1 = 0; i1 < words.length; ++i1){
for(int i = 0; i < arrayBad.length; ++i)
{
if(words[i1].equalsIgnoreCase(arrayBad[i])){
output.add(arrayBad[i] + " = " + arrayGood[i]);
}
}
}
StringBuilder out = new StringBuilder();
for( String s : output) {
out.append( s + "\n");
}
if(output.isEmpty()){
out.append("There are no detected gender specific words within your submitted message");
}
outputFinal = out.toString();
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(outputFinal);
// Set the text view as the activity layout
setContentView(textView);
}
}
LOGCAT
11-06 19:55:40.031: E/AndroidRuntime(28865): FATAL EXCEPTION: main
11-06 19:55:40.031: E/AndroidRuntime(28865): Process: com.example.android, PID: 28865
11-06 19:55:40.031: E/AndroidRuntime(28865): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android/com.example.android.Translated}: java.lang.NullPointerException: lock == null
11-06 19:55:40.031: E/AndroidRuntime(28865): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2411)
11-06 19:55:40.031: E/AndroidRuntime(28865): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
11-06 19:55:40.031: E/AndroidRuntime(28865): at android.app.ActivityThread.access$800(ActivityThread.java:144)
11-06 19:55:40.031: E/AndroidRuntime(28865): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
11-06 19:55:40.031: E/AndroidRuntime(28865): at android.os.Handler.dispatchMessage(Handler.java:102)
11-06 19:55:40.031: E/AndroidRuntime(28865): at android.os.Looper.loop(Looper.java:155)
11-06 19:55:40.031: E/AndroidRuntime(28865): at android.app.ActivityThread.main(ActivityThread.java:5696)
11-06 19:55:40.031: E/AndroidRuntime(28865): at java.lang.reflect.Method.invoke(Native Method)
11-06 19:55:40.031: E/AndroidRuntime(28865): at java.lang.reflect.Method.invoke(Method.java:372)
11-06 19:55:40.031: E/AndroidRuntime(28865): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
11-06 19:55:40.031: E/AndroidRuntime(28865): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
11-06 19:55:40.031: E/AndroidRuntime(28865): Caused by: java.lang.NullPointerException: lock == null
11-06 19:55:40.031: E/AndroidRuntime(28865): at java.io.Reader.<init>(Reader.java:64)
11-06 19:55:40.031: E/AndroidRuntime(28865): at java.io.InputStreamReader.<init>(InputStreamReader.java:120)
11-06 19:55:40.031: E/AndroidRuntime(28865): at java.io.InputStreamReader.<init>(InputStreamReader.java:57)
11-06 19:55:40.031: E/AndroidRuntime(28865): at com.example.android.Translated.onCreate(Translated.java:51)
11-06 19:55:40.031: E/AndroidRuntime(28865): at android.app.Activity.performCreate(Activity.java:5958)
11-06 19:55:40.031: E/AndroidRuntime(28865): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129)
11-06 19:55:40.031: E/AndroidRuntime(28865): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
11-06 19:55:40.031: E/AndroidRuntime(28865): ... 10 more
If you want me to sift through this and return only the important Boolean parts, then I can do that. Just ask. It seems like a made a pretty basic error, and I really really need help on this. Thanks! Any ideas where I need to add in a if(num != null), or if I even need to?
If you are passing information through intent then use
startActivityForResult(intent) instead of startActivity(intent)
Are you sure this line is absolutely correct com.robertb.TRANSLATED ?
And what you want to do in this?
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
And finally, have you defined this new activity in androidManifest?

android Unable to start activity ComponentInfo NULL Point Exception

My app work strange on diffrent phones - once everything is fine and other time it crash when i try to make photo and save it in my phone's memory. Photo shows up in folder in memory, but when we should come back to application it is shut down:
06-14 23:58:37.448 12344-12344/com.apps.madzia.photo_application E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.apps.madzia.photo_application, PID: 12344
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.apps.madzia.photo_application/com.apps.madzia.photo_application.activity.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2412)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4053)
at android.app.ActivityThread.access$1000(ActivityThread.java:174)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1313)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5593)
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:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
at android.widget.GridView.setAdapter(GridView.java:187)
at com.apps.madzia.photo_application.fragments.FragmentGallery.onCreateView(FragmentGallery.java:42)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:1917)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:544)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1177)
at android.app.Activity.performStart(Activity.java:5468)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2385)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4053)
            at android.app.ActivityThread.access$1000(ActivityThread.java:174)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1313)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5593)
            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:1283)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
            at dalvik.system.NativeStart.main(Native Method)
The code of my function to make photos:
public void make_photo() {
Calendar c;
c = Calendar.getInstance();
imageName = "fotka_" + c.get(Calendar.YEAR) + "_" + c.get(Calendar.MONTH) + "_" + c.get(Calendar.DAY_OF_MONTH)
+ "_" + c.get(Calendar.HOUR_OF_DAY) + "_" + c.get(Calendar.MINUTE) + "_" + c.get(Calendar.SECOND);
File katalog = new File(IMAGE_FILE_PATH);
File photo = new File(IMAGE_FILE_PATH+imageName + ".jpg");
if( Environment.getExternalStorageState() == Environment.MEDIA_UNKNOWN || Environment.getExternalStorageState() == Environment.MEDIA_REMOVED || Environment.getExternalStorageState() == Environment.MEDIA_UNMOUNTED) {
Log.d("ExternalStorage", "cannot find memory SD card");
File file = new File(getFilesDir(), imageName);
IMAGE_FILE_PATH = file.getParent()+"/";
Log.d("IMAGE_FILE_PATH", IMAGE_FILE_PATH);
}else {
}
Log.d("photo", photo.getPath());
if (!katalog.exists()) {
katalog.mkdirs();
}
try {
// fotka = File.createNewFile(imageName, ".jpg", katalog);
photo.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Intent zdjecie = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
zdjecie.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
startActivityForResult(zdjecie, 1);
}
Caused by: java.lang.NullPointerException
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
at android.widget.GridView.setAdapter(GridView.java:187)
at com.apps.madzia.photo_application.fragments.FragmentGallery.onCreateView(FragmentGallery.java:42)
This means that in your FragmentGallery in onCreateView method on line 42 u are setting null ArrayAdapter

Error getting content from .txt file from URL

URL scoreU = null;
try {
scoreU = new URL("http://m.uploadedit.com/b044/1422550899503.txt");
} catch (MalformedURLException e) {
e.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(
new InputStreamReader(
scoreU.openStream()));
} catch (IOException e) {
e.printStackTrace();
}
String inputLine;
try {
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
That's my code related to getting the text from the URL. It's the first time I have done this and I cannot understand my mistake. (I had to surround almost everything with a try/catch .
ERROR:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.wc.gap.worldcupfixture/com.wc.gap.worldcupfixture.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:190)
at java.net.URL.openStream(URL.java:470)
at com.wc.gap.worldcupfixture.MainActivity.onCreate(MainActivity.java:102)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
new InputStreamReader(scoreU.openStream()));
Android doesn't allow network requests on the main thread as it can cause UI unresponsiveness. Instead you have to do the work on a background thread, but this is pretty easy with an AsyncTask, for example:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
// Start the task here
new URLDataLoader().execute(theURL);
}
private class URLDataLoader extends AsyncTask<URL, Void, String> {
#Override
protected String doInBackground(URL... params) {
URL theURL = params[0];
// Do your network stuff here to get the data
return theData;
}
#Override
protected void onPostExecute(String data) {
// Use the data here
}
}
}
Use this code:-
try {
URL url = new URL("http://m.uploadedit.com/b044/1422550899503.txt");
URLConnection urlConnection = url.openConnection();
HttpURLConnection connection = null;
connection = (HttpURLConnection) urlConnection;
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String urlString = "";
String current;
while ((current = in.readLine()) != null) {
urlString += current;
}
System.out.println(urlString);
} catch (IOException e) {
e.printStackTrace();
}

java.lang.NoClassDefFoundError

i was implmenting a pdf reader in my project when i got the following error..
E/AndroidRuntime(1495): FATAL EXCEPTION: main
E/AndroidRuntime(1495): Process: com.example.testqstn, PID: 1495
E/AndroidRuntime(1495): java.lang.NoClassDefFoundError: com.questionpoint.pdf.Pdf
E/AndroidRuntime(1495): at com.question_point.main.Question_Point_Main.openPdfIntent(Question_Point_Main.java:272)
E/AndroidRuntime(1495): at com.question_point.main.Question_Point_Main.CopyReadAssets(Question_Point_Main.java:266)
E/AndroidRuntime(1495): at com.question_point.main.Question_Point_Main.pdfSelection(Question_Point_Main.java:128)
E/AndroidRuntime(1495): at com.question_point.main.Question_Point_Main$2.onClick(Question_Point_Main.java:104)
E/AndroidRuntime(1495): at android.view.View.performClick(View.java:4438)
E/AndroidRuntime(1495): at android.view.View$PerformClick.run(View.java:18422)
E/AndroidRuntime(1495): at android.os.Handler.handleCallback(Handler.java:733)
E/AndroidRuntime(1495): at android.os.Handler.dispatchMessage(Handler.java:95)
E/AndroidRuntime(1495): at android.os.Looper.loop(Looper.java:136)
E/AndroidRuntime(1495): at android.app.ActivityThread.main(ActivityThread.java:5017)
E/AndroidRuntime(1495): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1495): at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime(1495): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
E/AndroidRuntime(1495): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
E/AndroidRuntime(1495): at dalvik.system.NativeStart.main(Native Method)
I/Process(1495): Sending signal. PID: 1495 SIG: 9
i had imported a project to my code.. my library file is named libs, and i have repeatedly cleaned my project.. but still the error persists.. Thanks in advance..
The code that leads to error
public void CopyReadAssets(String url) {
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), url);
try {
in = assetManager.open(url);
out = openFileOutput(file.getName(),
Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch (Exception e) {
Log.e("tag", e.getMessage());
}
String path = "file://" + getFilesDir() + "/"+url;
openPdfIntent(path);
}
private void openPdfIntent(String path) {
// TODO Auto-generated method stub
try {
final Intent intent = new Intent(Question_Point_Main.this, Pdf.class);
intent.putExtra(PdfViewerActivity.EXTRA_PDFFILENAME, path);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
Try these steps:
Step 1: Create a folder "lib", and copy all third-party jars here;
Step 2: Add these jars to build path;
Step 3: Use the folder as Source Folder(shown below).
Maybe you just forgot the underscore and you meant com.question_point.pdf.Pdf?
It would be easier to tell if you could post the relevant code where you make the call that leads to the Exception.

Categories