My Preferencescreen is not working on a real device - java

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"/>

Related

Can't add Items to spinner [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am having trouble adding items to my spinner from an Arraylist. I have it working in other parts of my code, but it wont work when I put it in my dialog.
The exact problem is that it causes the app to crash. The crash happens when I press the button to open the dialog.
Here is the problematic code:
public void transferButton(View view) {
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog_transfer);
ArrayList<String> file = new ArrayList();
List<String> accounts = new ArrayList();
File path = Environment.getExternalStorageDirectory();
File myExternalFile = new File(path.getAbsolutePath() + folderLoc, "accounts.txt");
try {
FileInputStream fis = new FileInputStream(myExternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
file.add(strLine);
}
br.close();
in.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
ArrayAdapter<String> adapter1 = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
ArrayAdapter<String> adapter2 = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner fromSpinner = (Spinner) view.findViewById(R.id.fromAccountSpinner);
Spinner toSpinner = (Spinner) view.findViewById(R.id.toAccountSpinner);
for (int i = 0; i < file.size(); i++) {
String[] splitArray = file.get(i).split("//");
adapter1.add(splitArray[0]);
adapter2.add(splitArray[0]);
}
adapter1.insert("From...", 0);
fromSpinner.setAdapter(adapter1);
adapter2.insert("To...", 0);
toSpinner.setAdapter(adapter2);
Button dialogButton = (Button) dialog.findViewById(R.id.closeButton);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
Here is the error log:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.gstraatsma.gsfinancetracker, PID: 14493
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
at android.view.View.performClick(View.java:6205)
at android.widget.TextView.performClick(TextView.java:11103)
at android.view.View$PerformClick.run(View.java:23653)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:6205) 
at android.widget.TextView.performClick(TextView.java:11103) 
at android.view.View$PerformClick.run(View.java:23653) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6682) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference
at com.gstraatsma.gsfinancetracker.MainActivity.transferButton(MainActivity.java:1258)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385) 
at android.view.View.performClick(View.java:6205) 
at android.widget.TextView.performClick(TextView.java:11103) 
at android.view.View$PerformClick.run(View.java:23653) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6682) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410) 
Change view.findViewById(R.id.fromAccountSpinner); to dialog.findViewById(R.id.fromAccountSpinner);

Cannot retrieve the data when trying to login the system (Android Studio)

I'm begginer in Android programming, I'm trying to make the login function. This system will be accessed by two users which are admin and users. The admin just need to enter the "admin" for the username and password to access the system. However, the users needs to register their account before login the system.
I'm trying to find the errors but still don't know the error occurrence. Please help me to solve the errors. Thank You.
DatabaseOperations.java
public Cursor getInformation(DatabaseOperations dob)
{
SQLiteDatabase database=dob.getReadableDatabase();
String[] columns={TableInfo.USERNAME,TableInfo.USERPASS};
Cursor cr=database.query(TableInfo.TABLE_NAME,columns,null,null,null,null,null);
return cr;
}
MainActivity.java
public void onClick(View view)
Toast.makeText(getBaseContext(), "Please wait....", Toast.LENGTH_LONG).show();
txtusername = Username.getText().toString();
txtpassword = Password.getText().toString();
DatabaseOperations dop = new DatabaseOperations(this, null, null, 1);
Cursor CR = dop.getInformation(dop);
CR.moveToFirst();
boolean login_status = false;
String NAME = "";
if (txtusername.equals("Admin") && (txtpassword).equals("Admin")) {
Intent in = new Intent(MainActivity.this, AdminMenu.class);
startActivity(in);
} else {
do {
if (txtusername.equals(CR.getString(0)) && (txtpassword.equals(CR.getString(1)))) {
login_status = true;
NAME = CR.getString(0);
}
} while (CR.moveToNext());
if (login_status) {
Toast.makeText(getBaseContext(), "Login Success....\n Welcome " + NAME, Toast.LENGTH_LONG).show();
Intent i=new Intent(MainActivity.this,UserMenu.class);
Bundle bundle=new Bundle();
bundle.putString("username",NAME);
i.putExtras(bundle);
startActivity(i);
finish();
} else {
Toast.makeText(getBaseContext(), "Login Failed...", Toast.LENGTH_LONG).show();
Intent i = new Intent();
Bundle bundle=new Bundle();
bundle.putString("username",NAME);
i.putExtras(bundle);
startActivity(i);
finish();
}
}
}
This is the error...
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.google.mobile_flexi_parking, PID: 6777
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5198) 
at android.view.View$PerformClick.run(View.java:21147) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Caused by: android.content.ActivityNotFoundException: No Activity found to handle Intent { (has extras) }
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1798)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1512)
at android.app.Activity.startActivityForResult(Activity.java:3917)
at android.app.Activity.startActivityForResult(Activity.java:3877)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:842)
at android.app.Activity.startActivity(Activity.java:4200)
at android.app.Activity.startActivity(Activity.java:4168)
at com.google.mobile_flexi_parking.MainActivity.onclickLogin(MainActivity.java:67)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:5198) 
at android.view.View$PerformClick.run(View.java:21147) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
In your else part you have blank intent which doesn't point any activity
Intent i = new Intent();
I think this is causing error.

Bitmap returns null when taking screenshot

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;

BufferedRead runtime crash

My app crash when encounters BufferedReader operation. Ive tried to implement the code inside an asyncTask classe, because ive read that the crash is caused by the ui thread, but nothing has changed.
public class URLConnectionReader extends AsyncTask<URL, Void, String> {
String result = null;
#Override
protected String doInBackground(URL... params) {
String result = null;
URL url = (params[0]);
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(
url.openStream()
)
);
}catch (IOException e){
e.printStackTrace();
}
return result;
}
}
Logs
03-02 13:28:43.215 25186-25186/com.example.jsonreader E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.jsonreader, PID: 25186
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jsonreader/com.example.jsonreader.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.example.jsonreader.URLConnectionReader.doInBackground(URLConnectionReader.java:38)
at com.example.jsonreader.MainActivity.onCreate(MainActivity.java:27)
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)
MainActivity code
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
URL address = new URL("http://www.youth-stories.com/api/all.php");
URLConnectionReader reader = new URLConnectionReader();
String result = reader.doInBackground(address);
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
}catch (IOException e){
e.printStackTrace();
}
i solved the problem to get back data using the .get instruction
String result = reader.execute(address).get();

Check if Internet Connection Is Active In Android

i am trying to check for internet connection in my application.
first, i am checking if wifi or mobile data is on, then i am checking if there is an active internet connection.
what i am currently doing:
public class ConnectivityReceiver extends BroadcastReceiver {
String TAG="ConnectivityReceiver";
public static boolean hasInternetAccess() {
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 204 &&
urlc.getContentLength() == 0);
} catch (IOException e) {
}
return false;
}
#Override
public void onReceive(Context arg0, Intent intent) {
String action = intent.getAction();
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,false);
if(noConnectivity){
try{
TaskListAndOptionsActivity.item3.setIcon(R.drawable.ic_action_network_nowifi);
}
catch(Exception e)
{
}
}
else
{
Boolean status = hasInternetAccess();
if(status==true)
{
try{
TaskListAndOptionsActivity.item3.setIcon(R.drawable.ic_action_network_wifi);
}
catch(Exception e)
{
}
}
else
{
try{
TaskListAndOptionsActivity.item3.setIcon(R.drawable.ic_action_network_nowifi);
}
catch(Exception e)
{
}
}
}
}
but i am getting the following error:
java.lang.RuntimeException: Unable to start receiver connectionchecker.ConnectivityReceiver: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2668)
at android.app.ActivityThread.access$1800(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5653)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1166)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:390)
at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:343)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:289)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
at connectionchecker.NetworkUtil.hasInternetAccess(NetworkUtil.java:21)
at connectionchecker.ConnectivityReceiver.onReceive(ConnectivityReceiver.java:46)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2653)
            at android.app.ActivityThread.access$1800(ActivityThread.java:172)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5653)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
            at dalvik.system.NativeStart.main(Native Method)
You are trying to connect to the network in UI thread which is not allowed. to check for active internet connection use following method.
public boolean isConnected() {
ConnectivityManager manager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
return true;
} else {
return false;
}
}
Once you receive the value, if it is true proceed with network operation. Else display the user a proper error message.
Caused by: android.os.NetworkOnMainThreadException
You need to perform network operation not on UIthread.
Sounds like you might need to use the getActiveNetworkInfo() call. There is a few posts on stackoverflow already that document it extensively so rather than repeat those have a look at these:
Detect whether there is an Internet connection available on Android

Categories