如何使用android studio修复上传图像中的FATAL EXCEPTION java.lang.NullPointerException?

时间:2017-02-08 04:21:58

标签: android json image android-volley

我被困在这里。问题是我必须使用凌空保存数据。如何保存它,程序总是强制关闭。保存时,“intaniryanti.golearnv1t

  

E / AndroidRuntime:致命异常:主要是   过程:com.intaniryanti.golearnv1t,PID:
  java.lang.NullPointerException:尝试调用虚方法'void   com.intaniryanti.golearnv1t.app.AppController.addToRequestQueue(com.android.volley.Request,   java.lang.String)'在null对象上   com.intaniryanti.golearnv1t.ProfileActivity.uploadImage(ProfileActivity.java:at   com.intaniryanti.golearnv1t.ProfileActivity.access $ 100(ProfileActivity.java:   在   com.intaniryanti.golearnv1t.ProfileActivity $ 2.onClick(ProfileActivity.java:   在android.view.View.performClick(View.java:
  在android.view.View $ PerformClick.run(View.java:
  在android.os.Handler.handleCallback(Handler.java:739)
  在android.os.Handler.dispatchMessage(Handler.java:95)

“这是我在AndroidManifest.xml中的代码。我不想用以下代码显示:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.intaniryanti.golearnv1t">

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality. 
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:name=".app.AppController"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/. 
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".SplashActivity"
            android:label="@string/app_name"
            android:noHistory="true"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MapsActivity"
            android:label="@string/app_name" />
        <activity android:name=".HomeActivity" />
        <activity android:name=".LoginActivity" />
        <activity android:name=".MainActivity" />
        <activity android:name=".Main2Activity" />
        <activity android:name=".CatchIMEI" />
        <activity android:name=".PermintaanActivity" />
        <activity
            android:name=".PesananActivity"
            android:label="@string/title_activity_pesanan"
            android:parentActivityName=".HomeActivity" />
        <activity
            android:name=".RatingActivity"
            android:label="@string/title_activity_rating"
            android:parentActivityName=".HomeActivity" />
        <activity
            android:name=".LayananActivity"
            android:label="@string/title_activity_layanan"
            android:parentActivityName=".HomeActivity"></activity>
        <activity android:name=".ProfileActivity"></activity>
    </application>

</manifest>

ProfileActivity.java

package com.intaniryanti.golearnv1t;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.intaniryanti.golearnv1t.app.AppController;

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

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ProfileActivity extends AppCompatActivity {
    Button buttonChoose;
    Button buttonUpload;
    ImageView imageView;
    EditText txt_name;
    Bitmap bitmap;
    int success;
    int PICK_IMAGE_REQUEST = 1;

    private static final String TAG = MainActivity.class.getSimpleName();

    // sesuiakan ip address laptop/pc atau ip emulator android bawaan 10.0.2.2
    private String UPLOAD_URL ="http://192.168.43.176/GOLearn/upload1.php";

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";
    private String KEY_IMAGE = "image";
    private String KEY_NAME = "name";

    String tag_json_obj = "json_obj_req";

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

        buttonChoose = (Button) findViewById(R.id.buttonChoose);
        buttonUpload = (Button) findViewById(R.id.buttonUpload);

        txt_name = (EditText) findViewById(R.id.editText);

        imageView  = (ImageView) findViewById(R.id.imageView);

        buttonChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showFileChooser();
            }
        });

        buttonUpload.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                uploadImage();
            }
        });

    }

    public String getStringImage(Bitmap bmp){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }

    private void uploadImage(){
        //menampilkan progress dialog
        final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d(TAG, "Response: " + response.toString());

                        try {
                            JSONObject jObj = new JSONObject(response);
                            success = jObj.getInt(TAG_SUCCESS);

                            if (success == 1) {
                                Log.d("v Add", jObj.toString());

                                Toast.makeText(ProfileActivity.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();

                                kosong();

                            } else {
                                Toast.makeText(ProfileActivity.this, jObj.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        //menghilangkan progress dialog
                        loading.dismiss();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //menghilangkan progress dialog
                        loading.dismiss();

                        //menampilkan toast
                        Toast.makeText(ProfileActivity.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
                        Log.d(TAG, error.getMessage().toString());
                    }
                }){
            @Override
            protected Map<String, String> getParams() {
                //membuat parameters
                Map<String,String> params = new HashMap<String, String>();

                //menambah parameter yang di kirim ke web servis
                params.put(KEY_IMAGE, getStringImage(bitmap));
                params.put(KEY_NAME, txt_name.getText().toString().trim());

                //kembali ke parameters
                Log.d(TAG, ""+params);
                return params;
            }
        };

        AppController.getInstance().addToRequestQueue(stringRequest, tag_json_obj);
    }

    private void showFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri filePath = data.getData();
            try {
                //mengambil fambar dari Gallery
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                //menampilkan gambar yang dipilih dari gallery ke ImageView
                imageView.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void kosong(){
        imageView.setImageResource(0);
        txt_name.setText(null);
    }
}

摇篮

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.2.0'
    compile 'com.google.android.gms:play-services:9.4.0'
    compile 'com.android.support:design:24.2.0'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'com.android.support:cardview-v7:24.2.0'
    compile 'com.android.support:support-v4:24.2.0'
    compile 'com.google.android.gms:play-services-ads:9.4.0'
    compile 'com.google.android.gms:play-services-auth:9.4.0'
    compile 'com.google.android.gms:play-services-gcm:9.4.0'
}

套餐应用 - &gt; AppController.java

package com.intaniryanti.golearnv1t.app;

import android.app.Application;
import android.text.TextUtils;

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

import com.intaniryanti.golearnv1t.volley.LruBitmapCache;

public class AppController extends Application {

    public static final String TAG = AppController.class.getSimpleName();

    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    LruBitmapCache mLruBitmapCache;

    private static AppController mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public ImageLoader getImageLoader() {
        getRequestQueue();
        if (mImageLoader == null) {
            getLruBitmapCache();
            mImageLoader = new ImageLoader(this.mRequestQueue, mLruBitmapCache);
        }

        return this.mImageLoader;
    }

    public LruBitmapCache getLruBitmapCache() {
        if (mLruBitmapCache == null)
            mLruBitmapCache = new LruBitmapCache();
        return this.mLruBitmapCache;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

logcat的

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.intaniryanti.golearnv1t, PID:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.intaniryanti.golearnv1t.app.AppController.addToRequestQueue(com.android.volley.Request, java.lang.String)' on a null object at com.intaniryanti.golearnv1t.ProfileActivity.uploadImage(ProfileActivity.java:at com.intaniryanti.golearnv1t.ProfileActivity.access$100(ProfileActivity.java: at com.intaniryanti.golearnv1t.ProfileActivity$2.onClick(ProfileActivity.java: at android.view.View.performClick(View.java:
at android.view.View$PerformClick.run(View.java:
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)

请帮助

1 个答案:

答案 0 :(得分:0)

请提供档案.app.AppController的代码,以便我们找出问题。

希望你正在使用

public class AppController extends Application {

private static AppController mInstance;
private RequestQueue mRequestQueue;

@Override
public void onCreate() {
    super.onCreate();
    mInstance = this;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    return mRequestQueue;
}

}