I trying to get simple json from URL. But I get exception on line c.connect(). I added permission for Internet in manifest.
Tried 5-6 codes, but everytime I get break on connection everytime. In debbuging I get response code -1 but going to final block on c.connect() line.
String result = getJSON("http://api.wipmania.com/json");
public String getJSON(String url) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(newInputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
Here is Log:
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: FATAL EXCEPTION: main
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: Process: com.testapp.alex.testmaapp, PID: 2529
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.testapp.alex.testmaapp/com.testapp.alex.testmaapp.SumActivity}: android.os.NetworkOnMainThreadException
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.ActivityThread.-wrap11(ActivityThread.java)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: Caused by: android.os.NetworkOnMainThreadException
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at java.net.InetAddress.getAllByName(InetAddress.java:215)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.testapp.alex.testmaapp.SumActivity.makeRequest(SumActivity.java:82)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.testapp.alex.testmaapp.SumActivity.onCreate(SumActivity.java:51)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:6237)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.ActivityThread.-wrap11(ActivityThread.java)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
10-28 13:00:13.111 2529-2529/com.testapp.alex.testmaapp E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
The logcat you posted suggests that you are trying to make this call on Main Thread and it isn't possible, so you have to start another Trhead; check this:
final Runnable connect = new Runnable() {
Handler progress = new Handler();
#Override
public void run() {
String response = getJSON("http://api.wipmania.com/json");
progress.post(new Runnable() {
#Override
public void run() {
//do what you want with response
}
});
}
};
and call in this way:
new Thread(connect).start();
Anyway there are a lot of libraries that make http request for you, in a very simple way.
Check for Robospice or for Retrofit.
In my last project I used Retrofit, and it's very comfortable.
This is another guide for using Retrofit
try this code
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(
"http://bla/bla/bla");
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
You have already opened connection with u.openConnection(); so don't need to call c.connect().
Check this link for more information:
Try this way:
public String makeRequest(String uri, String json) {
HttpURLConnection urlConnection;
String data = json;
String result = null;
try {
// Connect
urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
urlConnection.setDoOutput(true);
urlConnection
.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.connect();
// Write
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
outputStream, "UTF-8"));
writer.write(data);
writer.close();
outputStream.close();
// Read
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream(),
"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
result = sb.toString();
System.out.println("result result result: " + result.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
Related
I want to connect my login page to MySQL PHP but I got some error here.
This is my logcat:
807/com.aeu.mlibrary.mlibraryaeu E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.aeu.mlibrary.mlibraryaeu, PID: 1807
java.lang.ClassCastException: com.aeu.mlibrary.mlibraryaeu.LoginFragment cannot be cast to android.content.Context
at com.kosalgeek.asynctask.PostResponseAsyncTask.<init>(PostResponseAsyncTask.java:284)
at com.aeu.mlibrary.mlibraryaeu.LoginFragment.onClick(LoginFragment.java:82)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
and this is the error line in my loginFragment.java:
#Override
public void onClick(View v) {
HashMap postData = new HashMap();
postData.put("mobile", "android");
postData.put("txtUsername", etUsername.getText().toString());
postData.put("txtPassword", etPassword.getText().toString());
PostResponseAsyncTask task = new PostResponseAsyncTask(LoginFragment.this, postData);
task.execute("http://10.0.3.2/mlibrary/HTML/login.php");
}
I need your help guys!
Thank you.
Replace LoginFragment.this with getActvity()
PostResponseAsyncTask task = new PostResponseAsyncTask(getActivity(), postData);
Replace LoginFragment.this with getContext() :
PostResponseAsyncTask task = new PostResponseAsyncTask(getContext(), postData);
I am working on android GCM to display some notification. It works fine. But when I add a code that could enable me to start the Home activity upon clicking the notification, it crashes. If I remove the PendingIntent It works fine but with no action.
Below is the code I am using
public class GcmMessageHandler extends GcmListenerService {
public static final int MESSAGE_NOTIFICATION_ID = 435345;
Intent intent = new Intent(GcmMessageHandler.this, HomeActivity.class);
int requestID = (int) System.currentTimeMillis(); //unique requestID to differentiate between various notification with same NotifId
int flags = PendingIntent.FLAG_CANCEL_CURRENT; // cancel old intent and create new one
PendingIntent pIntent = PendingIntent.getActivity(this, requestID, intent, flags);
#Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
createNotification(from, message);
}
// Creates notification based on title and body received
private void createNotification(String title, String body) {
Context context = getBaseContext();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.setContentIntent(pIntent);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(MESSAGE_NOTIFICATION_ID, mBuilder.build());
}
}
and below is the error log I am getting.
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: FATAL EXCEPTION: main
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: Process: abenakebe.yournet.com.abenakebe, PID: 14201
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: java.lang.RuntimeException: Unable to instantiate service abenakebe.yournet.com.abenakebe.utils.GcmMessageHandler: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.content.Context.getContentResolver()' on a null object reference
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.app.ActivityThread.handleCreateService(ActivityThread.java:3623)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.app.ActivityThread.access$2000(ActivityThread.java:198)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1759)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.os.Looper.loop(Looper.java:145)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:6837)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:372)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.content.Context.getContentResolver()' on a null object reference
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.content.ContextWrapper.getContentResolver(ContextWrapper.java:101)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.app.PendingIntent.getActivity(PendingIntent.java:286)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.app.PendingIntent.getActivity(PendingIntent.java:252)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at abenakebe.yournet.com.abenakebe.utils.GcmMessageHandler.<init>(GcmMessageHandler.java:25)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at java.lang.reflect.Constructor.newInstance(Native Method)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at java.lang.Class.newInstance(Class.java:1684)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.app.ActivityThread.handleCreateService(ActivityThread.java:3620)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.app.ActivityThread.access$2000(ActivityThread.java:198)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1759)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.os.Looper.loop(Looper.java:145)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:6837)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:372)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
04-14 23:24:59.165 14201-14201/abenakebe.yournet.com.abenakebe E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
You should move this two things at least to onCreate() or onMessageReceived()
Intent intent = new Intent(GcmMessageHandler.this, HomeActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, requestID, intent, flags);
It crashes because this doesn't have Context before onCreate was called.
SHould be like this:
public class GcmMessageHandler extends GcmListenerService {
public static final int MESSAGE_NOTIFICATION_ID = 435345;
Intent intent;
int requestID = (int) System.currentTimeMillis(); //unique requestID to differentiate between various notification with same NotifId
int flags = PendingIntent.FLAG_CANCEL_CURRENT; // cancel old intent and create new one
PendingIntent pIntent;
#Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
intent = new Intent(GcmMessageHandler.this, HomeActivity.class);
pIntent = PendingIntent.getActivity(this, requestID, intent, flags);
createNotification(from, message);
}
// Creates notification based on title and body received
private void createNotification(String title, String body) {
Context context = getBaseContext();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.setContentIntent(pIntent);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(MESSAGE_NOTIFICATION_ID, mBuilder.build());
}
}
I am attempting to add a Facebook Login to my Android application. When I launch the application at first, it logs in without any issues, but afterwards, anytime I try to log in, the application crashes.
The MainActivity.java is as follows:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this.getApplicationContext());
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
List<String> permissionNeeds = Arrays.asList("public_profile", "user_friends");
loginButton.setReadPermissions(permissionNeeds);
try {
PackageInfo info = getPackageManager().getPackageInfo("com.example.ryans_000.facebooklogin", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
System.out.println("onSuccess");
}
#Override
public void onCancel() {
System.out.println("onCancel");
}
#Override
public void onError(FacebookException exception) {
Log.v("LoginActivity", exception.getCause().toString()); }
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}}
The content_main contains the following piece of code for the button:
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
android:layout_marginBottom="30dp" />
The Logcat is showing up the following:
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: FATAL EXCEPTION: main
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: Process: com.example.ryans_000.facebooklogin, PID: 23263
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=64206, result=-1, data=Intent { (has extras) }} to activity {com.example.ryans_000.facebooklogin/com.example.ryans_000.facebooklogin.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Throwable.toString()' on a null object reference
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at android.app.ActivityThread.deliverResults(ActivityThread.java:3988)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at android.app.ActivityThread.handleSendResult(ActivityThread.java:4038)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at android.app.ActivityThread.access$1400(ActivityThread.java:150)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1443)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at android.os.Looper.loop(Looper.java:168)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5845)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Throwable.toString()' on a null object reference
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at com.example.ryans_000.facebooklogin.MainActivity$1.onError(MainActivity.java:92)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at com.facebook.login.LoginManager.finishLogin(LoginManager.java:579)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at com.facebook.login.LoginManager.onActivityResult(LoginManager.java:216)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at com.facebook.login.LoginManager$1.onActivityResult(LoginManager.java:159)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at com.facebook.internal.CallbackManagerImpl.onActivityResult(CallbackManagerImpl.java:82)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at com.example.ryans_000.facebooklogin.MainActivity.onActivityResult(MainActivity.java:100)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at android.app.Activity.dispatchActivityResult(Activity.java:6439)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at android.app.ActivityThread.deliverResults(ActivityThread.java:3984)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at android.app.ActivityThread.handleSendResult(ActivityThread.java:4038)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at android.app.ActivityThread.access$1400(ActivityThread.java:150)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1443)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at android.os.Looper.loop(Looper.java:168)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5845)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
02-29 09:34:45.306 23263-23263/com.example.ryans_000.facebooklogin E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
I think in your
#Override
public void onError(FacebookException exception) {
Log.v("LoginActivity", exception.getCause().toString()); }
exception.getCause is null hence trying to convert it to string is showing null pointer exception. Try fixing that.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Throwable.toString()' on a null object reference
Most probably,it points out to the line that has used toString() method which is in onError(), So try changing that.
Good Luck!
I want to download a 100MB file using streams:
I used an AsyncTask class to make download:
#Override
protected Void doInBackground(String... params) {
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
inputStream = connection.getInputStream();
outputStream = new FileOutputStream(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), params[1]));
byte[] data = new byte[104857600];
int length = inputStream.read(data);
outputStream.write(data, 0, length);
} catch (Exception e) {
Log.e(TAG, "Unable to download file with DownloadTask: " + e.getMessage());
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
connection.disconnect();
} catch (Exception e) {
Log.e(TAG, "Unable to cancel download file with DownloadTask: " + e.getMessage());
}
}
return null;
}
I'm sure I used the following permissions:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
But when I test my app, it crashes and I see in logcat Out of memory on a 104857616-byte allocation:
10-02 10:28:35.578 29630-2246/com.example.myapp E/dalvikvm-heap: Out of memory on a 104857616-byte allocation.
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at android.os.AsyncTask$3.done(AsyncTask.java:299)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:239)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.lang.Thread.run(Thread.java:856)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: Caused by: java.lang.OutOfMemoryError
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at com.example.myapp.DownloaderActivity$DownloadTask.doInBackground(DownloaderActivity.java:126)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at com.example.myapp.DownloaderActivity$DownloadTask.doInBackground(DownloaderActivity.java:107)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:234)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
10-02 10:28:35.601 29630-2246/com.example.myapp E/AndroidRuntime: at java.lang.Thread.run(Thread.java:856)
Is there some way to download large files or accept 104857600 bytes (100MB)?
You have write data portion by portion as chunk. System don't provide huge memory at once for an operation.
Replace those lines:
byte[] data = new byte[104857600];
int length = inputStream.read(data);
outputStream.write(data, 0, length);
by:
byte [] buffer = new byte[1024];
int bytesRead = 0;
while((bytesRead =input.read(buffer)) != -1) {
outputStream .write(buffer, 0,
bytesRead);
}
I try to create a socket client connection to a python server like this, but it throwss me an error. This is triggered via a button, which works. The server is running on a RPi, but that's not the problem since a Python client works on my PC.
try {
Socket s = new Socket("192.168.178.43", 24069);
InputStreamReader streamReader = new InputStreamReader(s.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
String advice = reader.readLine();
reader.close();
} catch (UnknownHostException e) {
System.err.println("Unknown Host.");
// System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection.");
System.err.println(e);
// System.exit(1);
}
Stacktrace:
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3823)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3818)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
at libcore.io.IoBridge.connect(IoBridge.java:112)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.Socket.startupSocket(Socket.java:567)
at java.net.Socket.tryAllAddresses(Socket.java:128)
at java.net.Socket.<init>(Socket.java:178)
at java.net.Socket.<init>(Socket.java:150)
at com.example.app.MainActivity.sendMessage(MainActivity.java:65)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3818)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
you can't do any long time process on the Main UI thread the reason for that to avoid the crash of your App if your operation failed
try to create new thread and do your work inside of it and if u want to pass any result to the UI u cant use
View.Post()
or
context.runOnUiThread()
this is an example of what you can do or you can use asynctask instead
new Thread(new Runnable() {
public void run() {
try {
Socket s = new Socket("192.168.178.43", 24069);
InputStreamReader streamReader = new InputStreamReader(s.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
String advice = reader.readLine();
reader.close();
} catch (UnknownHostException e) {
System.err.println("Unknown Host.");
// System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection.");
System.err.println(e);
// System.exit(1);
}
}
}).start();