现在的位置: 首页 > 问答 > 正文

Issue when compiling android application

2017年09月14日 问答 ⁄ 共 18670字 ⁄ 字号 暂无评论

Good evening. I am taking a course in android and having issues compiling the app.

I am currently following this tutorial. I have earlier set up a requestQueue for GET requests.

This is my MainActivity.java file:

package com.ticketapp.emailaddresss.ticketapp;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.facebook.AccessToken;

import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.login.LoginManager;
import com.facebook.share.model.ShareHashtag;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.widget.ShareDialog;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    Button button;
    TextView textView;
    String server_url = "https://www.idg.se/";
    RequestQueue requestQueue;

    private ShareDialog shareDialog;
    private String name, surname, imageUrl;
    private String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.bm);
        textView = (TextView) findViewById(R.id.txt);

        Bundle inBundle = getIntent().getExtras();
        name = inBundle.getString("name");
        surname = inBundle.getString("surname");
        imageUrl = inBundle.getString("imageUrl");

        TextView nameView = (TextView) findViewById(R.id.nameAndSurname);
        nameView.setText("" + name + " " + surname);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                StringRequest stringRequest = new StringRequest(Request.Method.POST, server_url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                    textView.setText(response);
                    //requestQueue.stop();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        textView.setText("Something went wrong");
                        error.printStackTrace();
                        //requestQueue.stop();
                    }
                });
                //requestQueue.add(stringRequest);
                SingletonRequestQueue.getmInstance(getApplicationContext()).addRequestQueue(stringRequest);
            }
        });
    }

    private void share() {
        shareDialog = new ShareDialog(this);
        List<String> taggedUserIds = new ArrayList<String>();
        taggedUserIds.add("{USER_ID}");
        taggedUserIds.add("{USER_ID}");
        taggedUserIds.add("{USER_ID}");

        ShareLinkContent content = new ShareLinkContent.Builder()
                .setContentUrl(Uri.parse("http://www.sitepoint.com"))
                .setContentTitle("This is a content title")
                .setContentDescription("This is a description")
                .setShareHashtag(new ShareHashtag.Builder().setHashtag("#sitepoint").build())
                .setPeopleIds(taggedUserIds)
                .setPlaceId("{PLACE_ID}")
                .build();

        shareDialog.show(content);
    }

    private void getPosts() {
        new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/posts", null, HttpMethod.GET, new GraphRequest.Callback() {
            public void onCompleted(GraphResponse response) {
                Log.e(TAG, response.toString());
            }
        }).executeAsync();
    }

    private void logout() {
        LoginManager.getInstance().logOut();
        Intent login = new Intent(MainActivity.this, LoginActivity.class);
        startActivity(login);
        finish();
    }

    //@Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.share:
                share();
                break;

            case R.id.getPosts:
                getPosts();
                break;

            case R.id.logout:
                logout();
                break;
        }
    }
}

LoginActivity.java

package com.ticketapp.emailaddress.ticketapp;

import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.MalformedURLException;
import java.net.URL;

public class LoginActivity extends AppCompatActivity {

    private CallbackManager callbackManager;
    private AccessTokenTracker accessTokenTracker;
    private ProfileTracker profileTracker;
    private LoginButton loginButton;
    private String firstName,lastName, email,birthday,gender;
    private URL profilePicture;
    private String userId;
    private String TAG = "LoginActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // FacebookSdk.sdkInitialize(this);
        //FacebookSdk.sdkInitialize(getApplicationContext());

        setContentView(R.layout.activity_login);
        callbackManager = CallbackManager.Factory.create();

        loginButton = (LoginButton) findViewById(R.id.login_button);
        loginButton.setHeight(100);
        loginButton.setTextColor(Color.WHITE);
        loginButton.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        loginButton.setCompoundDrawablePadding(0);

        loginButton.setReadPermissions("email", "user_birthday","user_posts");
        loginButton.registerCallback(callbackManager, callback);
    }

    FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(JSONObject object, GraphResponse response) {
                    Log.e(TAG,object.toString());
                    Log.e(TAG,response.toString());

                    try {
                        userId = object.getString("id");
                        profilePicture = new URL("https://graph.facebook.com/" + userId + "/picture?width=500&height=500");
                        if(object.has("first_name"))
                            firstName = object.getString("first_name");
                        if(object.has("last_name"))
                            lastName = object.getString("last_name");
                        if (object.has("email"))
                            email = object.getString("email");
                        if (object.has("birthday"))
                            birthday = object.getString("birthday");
                        if (object.has("gender"))
                            gender = object.getString("gender");

                        Intent main = new Intent(LoginActivity.this,MainActivity.class);
                        main.putExtra("name",firstName);
                        main.putExtra("surname",lastName);
                        main.putExtra("imageUrl",profilePicture.toString());
                        startActivity(main);
                        finish();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }
                }
            });
            //Here we put the requested fields to be returned from the JSONObject
            Bundle parameters = new Bundle();
            parameters.putString("fields", "id, first_name, last_name, email, birthday, gender");
            request.setParameters(parameters);
            request.executeAsync();
        }

        @Override
        public void onCancel() {
        }

        @Override
        public void onError(FacebookException e) {
            e.printStackTrace();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
        super.onActivityResult(requestCode, responseCode, intent);
        callbackManager.onActivityResult(requestCode, responseCode, intent);
    }
}

SingletonRequestQueue.java

package com.ticketapp.emailaddress.ticketapp;

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

import java.lang.ref.ReferenceQueue;

/**
 * Created by Adde on 2017-09-11.
 */

public class SingletonRequestQueue {
    private
    static SingletonRequestQueue mInstance;
    private RequestQueue requestQueue;
    private static Context mCtx;


    private SingletonRequestQueue(Context context){
         mCtx = context;
        requestQueue = getRequestQueue();
    }

    public RequestQueue getRequestQueue(){

        if(requestQueue == null){
            requestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return requestQueue;
    }
    public static synchronized SingletonRequestQueue getmInstance(Context context) {
        if(mInstance == null){
            mInstance = new SingletonRequestQueue(context);
        }
        return mInstance;
    }

    public<T> void addRequestQueue(Request<T> request){
        requestQueue.add(request);
    }
}

build.gradle (module)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "com.ticketapp.myName.ticketapp"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    //FB SDK
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'

    // compile 'com.android.support:design:26.0.1'
    // compile 'com.android.support:appcompat-v7:26.0.1'

    // compile 'com.android.support:multidex:1.0.1'
    // Firebase

    // Volley
    // compile 'com.android.volley:volley:1.0.0'

    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.firebase:firebase-auth:11.2.2'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    //compile "com.google.android.gms:play-services-location:11.2.2"

    testCompile 'junit:junit:4.12'
}

// Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'

build.gradle (app)

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()

        //FB SDK
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        // Add this line
        classpath 'com.google.gms:google-services:3.1.0'
    }
}

allprojects {
    repositories {

        jcenter()

        //FB SDK
        maven {
            url "https://maven.google.com" // Google's Maven repository
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

logcat message

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ticketapp.myname.ticketapp, PID: 9650
java.lang.RuntimeException: Unable to start activity 

ComponentInfo{com.ticketapp.myname.ticketapp/com.ticketapp.myname.ticketapp.MainActivity}: android.view.InflateException: Binary XML file line #14: Binary XML file line #14: Error inflating class com.facebook.login.widget.LoginButton
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

Caused by: android.view.InflateException: Binary XML file line #14: Binary XML file line #14: Error inflating class com.facebook.login.widget.LoginButton
Caused by: android.view.InflateException: Binary XML file line #14: Error inflating class com.facebook.login.widget.LoginButton
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
at android.view.LayoutInflater.createView(LayoutInflater.java:647)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.ticketapp.myname.ticketapp.MainActivity.onCreate(MainActivity.java:49)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

Caused by: The SDK has not been initialized, make sure to call FacebookSdk.sdkInitialize() first.
at com.facebook.internal.Validate.sdkInitialized(Validate.java:145)
at com.facebook.AccessTokenTracker.<init>(AccessTokenTracker.java:55)
at com.facebook.login.widget.LoginButton$2.<init>(LoginButton.java:581)
at com.facebook.login.widget.LoginButton.configureButton(LoginButton.java:581)
at com.facebook.FacebookButtonBase.<init>(FacebookButtonBase.java:64)
at com.facebook.login.widget.LoginButton.<init>(LoginButton.java:210)
at java.lang.reflect.Constructor.newInstance0(Native Method) 
at java.lang.reflect.Constructor.newInstance(Constructor.java:334) 
at android.view.LayoutInflater.createView(LayoutInflater.java:647) 
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790) 
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863) 
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:515) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:423) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:374) 
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) 
at com.ticketapp.myname.ticketapp.MainActivity.onCreate(MainActivity.java:49) 
at android.app.Activity.performCreate(Activity.java:6975) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 

Manifest

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET" />

<activity
    android:name="com.facebook.CustomTabActivity"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />

        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />

        <data android:scheme="@string/fb_login_protocol_scheme" />
    </intent-filter>
</activity>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <meta-data
        android:name="com.facebook.sdk.ApplicationId"
        android:value="Secretokrn" />

    <activity
        android:name="com.facebook.FacebookActivity"
        android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
        android:label="@string/app_name"
        android:screenOrientation="portrait" />


    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <provider
        android:name="com.facebook.FacebookContentProvider"
        android:authorities="com.facebook.app.FacebookContentProviderSecretToken"
        android:exported="true" />

    <activity android:name=".LoginActivity"></activity>
</application>

strings.xml

<resources>
    <string name="app_name">TicketApp</string>
    <string name="facebook_app_id">SecretToken</string>
    <string name="fb_login_protocol_scheme">fbSecretToken</string>
    <string name="app_id">$app_id_here</string>
    <string name="ShareContent">Share Content</string>
    <string name="Posts">Posts</string>
    <string name="Logout">Logout</string>
    <string name="Hello">Hello</string>
</resources>

I hope I have included enough for a replicating this or solving it without testing.

Updated catlog.

09-12 15:13:21.988 5675-5675/com.ticketapp.myname.ticketapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ticketapp.myname.ticketapp, PID: 5675
java.lang.RuntimeException: Unable to start activity 
ComponentInfo{com.ticketapp.myname.ticketapp/com.ticketapp.myname.ticketapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at com.ticketapp.myname.ticketapp.MainActivity.onCreate(MainActivity.java:76)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 

Ok guys! New update! Apparently there was an issue in the code so I put a try and catch and the application worked. Unfortunately when u log in nothing displays at the moment. This is what I changed in the MainActivity.java

try {
    name = inBundle.getString("name");
    surname = inBundle.getString("surname");
    imageUrl = inBundle.getString("imageUrl");
    TextView nameView = (TextView) findViewById(R.id.nameAndSurname);
    nameView.setText("" + name + " " + surname);
} catch (Exception e){
    Log.e("Error on setContent", e.getMessage());
}

给我留言

您必须 [ 登录 ] 才能发表留言!

×