-2

I decided to make payment simulation using Stripe API. I did some things. But I have some problems with connection to server. At first I add some credit card info then I send it to server and from server send to my account in Stripe website. For back-end I used NodeJS. For connection to server I read this documentation from Google. By the way I did this certification for HTTPS. But I have some problems with function doInBackground. Android Monitor shows me doInBackground(DataBaseTask.java:211) - it shows this line InputStream caInput = new BufferedInputStream(contexting.getAssets().open("cert.pem")); And other line of code is class Example extends AsyncTask<String, Void, String>. Please help me.

This is my code:

public class DataBaseTask extends Activity{

      String command = "";
      Token token;

      public DataBaseTask(String mCommand, Token mToken) {
          command = mCommand;
          token = mToken;
          Log.e("Helloooo", "Helloooo DATABASETASK");
          new Example().execute();
      }

      class Example extends AsyncTask<String, Void, String> {

          @Override
          protected void onPreExecute() {
              super.onPreExecute();
              Log.e("AsyncTask", "onPreExecute");
          }

          @Override
          protected String doInBackground(String... params) {
              final Context contexting = DataBaseTask.this;
              Log.e("Context", contexting.toString());
              Log.e("Stop here", "Stop here");

              String echoData = "";

              if (command.equals("SANDTOKEN")) {
                  try {
                      // Load CAs from an InputStream
                      // (could be from a resource or ByteArrayInputStream or ...)
                      CertificateFactory cf = CertificateFactory.getInstance("X.509");

  //                    String fileName = "Download/cert.pem";
  //                    String path = Environment.getExternalStorageDirectory()+"/"+fileName;
  //                    File file = new File(path);
  //                    FileInputStream fileInputStream = new FileInputStream(file);

                      InputStream caInput = new BufferedInputStream(contexting.getAssets().open("cert.pem"));
                      Certificate ca = cf.generateCertificate(caInput);
                      System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
                      Log.e("ca", "ca= " + ((X509Certificate) ca).getSubjectDN());

                      // Create a KeyStore containing our trusted CAs
                      String keyStoreType = KeyStore.getDefaultType();
                      KeyStore keyStore = KeyStore.getInstance(keyStoreType);
                      keyStore.load(null, null);
                      keyStore.setCertificateEntry("ca", ca);

                      // Create a TrustManager that trusts the CAs in our KeyStore
                      String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
                      TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
                      tmf.init(keyStore);

                      // Create an SSLContext that uses our TrustManager
                      SSLContext context = SSLContext.getInstance("TLS");
                      context.init(null, tmf.getTrustManagers(), null);

                      // Tell the URLConnection to use a SocketFactory from our SSLContext
                      //URL url = new URL(urlString);
                      URL url = new URL("https://Address:4567/charge");

                      HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
                      connection.setSSLSocketFactory(context.getSocketFactory());

                      StringBuilder builder = new StringBuilder();
                      builder.append(URLEncoder.encode("stripeToken", "UTF-8"));
                      builder.append("=");
                      builder.append(URLEncoder.encode(token.getId(), "UTF-8"));
                      String urlParameters = builder.toString();

                      Log.e("String param ", urlParameters);

                      connection.setRequestMethod("POST");
                      connection.setDoOutput(true);

                      DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());

                      dStream.writeBytes(urlParameters);
                      dStream.flush();
                      dStream.close();

                      BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                      String line = "";
                      StringBuilder responseOutput = new StringBuilder();

                      while ((line = br.readLine()) != null) {
                          Log.e("DatabaseTask", line);
                          responseOutput.append(line);
                      }
                      br.close();
                      echoData = responseOutput.toString();

                  } catch (MalformedURLException e) {
                      e.printStackTrace();
                  } catch (IOException e) {
                      e.printStackTrace();
                  } catch (CertificateException e) {
                      e.printStackTrace();
                  } catch (NoSuchAlgorithmException e) {
                      e.printStackTrace();
                  } catch (KeyStoreException e) {
                      e.printStackTrace();
                  } catch (KeyManagementException e) {
                      e.printStackTrace();
                  } catch (NullPointerException e) {
                      e.printStackTrace();
                  }
              }
              return echoData;
          }
          @Override
          protected void onPostExecute(String mData) {
              Log.e("DatabaseTask", "onPostExecute result: " + mData);
          }
      }
  }

This is error:

/com.example.lado.banksystem W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
  04-16 18:43:43.028 9539-10081/com.example.lado.banksystem W/System.err:     at android.content.ContextWrapper.getResources(ContextWrapper.java:86)
  04-16 18:43:43.028 9539-10081/com.example.lado.banksystem W/System.err:     at android.view.ContextThemeWrapper.getResourcesInternal(ContextThemeWrapper.java:127)
  04-16 18:43:43.028 9539-10081/com.example.lado.banksystem W/System.err:     at android.view.ContextThemeWrapper.getAssets(ContextThemeWrapper.java:116)
  04-16 18:43:43.028 9539-10081/com.example.lado.banksystem W/System.err:     at com.example.lado.banksystem.DataBaseTask$Example.doInBackground(DataBaseTask.java:211)
  04-16 18:43:43.028 9539-10081/com.example.lado.banksystem W/System.err:     at com.example.lado.banksystem.DataBaseTask$Example.doInBackground(DataBaseTask.java:184)
  04-16 18:43:43.028 9539-10081/com.example.lado.banksystem W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:305)
  04-16 18:43:43.028 9539-10081/com.example.lado.banksystem W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
  04-16 18:43:43.028 9539-10081/com.example.lado.banksystem W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
  04-16 18:43:43.028 9539-10081/com.example.lado.banksystem W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
  04-16 18:43:43.028 9539-10081/com.example.lado.banksystem W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
  04-16 18:43:43.028 9539-10081/com.example.lado.banksystem W/System.err:     at java.lang.Thread.run(Thread.java:761)
  04-16 18:43:43.038 9539-9539/com.example.lado.banksystem E/DatabaseTask: onPostExecute result: 
  04-16 18:43:43.276 1348-1399/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 1453867 , only wrote 1301760
  04-16 18:43:43.577 1648-1648/? W/WindowManager: Attempted to remove non-existing token: android.os.Binder@ab7749
  04-16 18:43:43.641 9539-9566/com.example.lado.banksystem D/EGL_emulation: eglMakeCurrent: 0xaf805120: ver 2 0 (tinfo 0xaf803700)
  04-16 18:43:43.721 9539-9566/com.example.lado.banksystem D/EGL_emulation: eglMakeCurrent: 0xaf805120: ver 2 0 (tinfo 0xaf803700)
  04-16 18:43:47.087 1648-1648/? W/WindowManager: Attempted to remove non-existing token: android.os.Binder@2d0384e
  04-16 18:43:47.090 1648-1648/? I/ActivityManager: Killing 4486:com.google.android.videos/u0a72 (adj 906): empty #17
  04-16 18:43:47.142 1648-2092/? D/ActivityManager: cleanUpApplicationRecord -- 4486
  04-16 18:43:47.177 9539-9566/com.example.lado.banksystem D/EGL_emulation: eglMakeCurrent: 0xaf805120: ver 2 0 (tinfo 0xaf803700)
  04-16 18:43:47.239 9539-9566/com.example.lado.banksystem D/EGL_emulation: eglMakeCurrent: 0xaf805120: ver 2 0 (tinfo 0xaf803700)
  04-16 18:43:50.599 1648-1648/? W/WindowManager: Attempted to remove non-existing token: android.os.Binder@c2bf18b
  04-16 18:44:00.020 1718-1933/? D/EGL_emulation: eglMakeCurrent: 0xaf805840: ver 2 0 (tinfo 0x8fb08040)
  04-16 18:45:56.131 2426-4002/? I/PlayCommon: [160] com.google.android.play.b.h.e(263): Preparing logs for uploading
  04-16 18:45:56.131 2426-4002/? I/PlayCommon: [160] com.google.android.play.b.h.e(267): No file ready to send
  04-16 18:46:34.768 1648-1657/? W/art: Suspending all threads took: 5.309ms
  04-16 18:46:34.783 1648-1657/? I/art: Background sticky concurrent mark sweep GC freed 31001(3MB) AllocSpace objects, 3(156KB) LOS objects, 14% free, 16MB/18MB, paused 6.889ms total 39.977ms
  04-16 18:47:23.958 2453-2683/? W/BasePeopleOperation: READ_CONTACTS permission is missing. Skipping loadCp2DataInner()
  04-16 18:47:25.306 2453-2679/? I/Icing: Indexing CB8C5EB878248DCF0E1D4B215E247F81A7F25A76 from com.google.android.apps.docs
  04-16 18:47:25.312 2453-2679/? I/Icing: Not enough disk space for indexing trimmable
  04-16 18:47:25.312 2453-2679/? I/Icing: Cannot sync trimmable corpus: no trimmable
  04-16 18:47:25.312 2453-2679/? I/Icing: Indexing done CB8C5EB878248DCF0E1D4B215E247F81A7F25A76
  04-16 18:47:25.312 2453-2679/? E/Icing: Aborting indexing of corpus internal.3p:DigitalDocument
  04-16 18:47:25.314 2453-2679/? I/Icing: Indexing 2823A4E8E883823DE65F5628FB978D4BAB6FAF3D from com.google.android.apps.docs
  04-16 18:47:25.314 2453-2679/? I/Icing: Not enough disk space for indexing trimmable
  04-16 18:47:25.314 2453-2679/? I/Icing: Cannot sync trimmable corpus: no trimmable
  04-16 18:47:25.314 2453-2679/? I/Icing: Indexing done 2823A4E8E883823DE65F5628FB978D4BAB6FAF3D
  04-16 18:47:25.314 2453-2679/? E/Icing: Aborting indexing of corpus internal.3p:SpreadsheetDigitalDocument
  04-16 18:47:25.314 2453-2679/? I/Icing: Indexing 1025AB1BD34441691C05DD1956DAC0055E9B9892 from com.google.android.apps.docs
  04-16 18:47:25.315 2453-2679/? I/Icing: Not enough disk space for indexing trimmable
  04-16 18:47:25.315 2453-2679/? I/Icing: Cannot sync trimmable corpus: no trimmable
  04-16 18:47:25.315 2453-2679/? I/Icing: Indexing done 1025AB1BD34441691C05DD1956DAC0055E9B9892
  04-16 18:47:25.315 2453-2679/? E/Icing: Aborting indexing of corpus internal.3p:PresentationDigitalDocument
  04-16 18:47:25.315 2453-2679/? I/Icing: Indexing 32815EDB0F7643A5A6F997853ED4BC43CC823D2A from com.google.android.apps.docs
  04-16 18:47:25.315 2453-2679/? I/Icing: Not enough disk space for indexing trimmable
  04-16 18:47:25.315 2453-2679/? I/Icing: Cannot sync trimmable corpus: no trimmable
  04-16 18:47:25.315 2453-2679/? I/Icing: Indexing done 32815EDB0F7643A5A6F997853ED4BC43CC823D2A
  04-16 18:47:25.315 2453-2679/? E/Icing: Aborting indexing of corpus internal.3p:TextDigitalDocument
  04-16 18:47:25.387 2453-2679/? I/Icing: Indexing CB8C5EB878248DCF0E1D4B215E247F81A7F25A76 from com.google.android.apps.docs
  04-16 18:47:25.387 2453-2679/? I/Icing: Not enough disk space for indexing trimmable
  04-16 18:47:25.387 2453-2679/? I/Icing: Cannot sync trimmable corpus: no trimmable
  04-16 18:47:25.387 2453-2679/? I/Icing: Indexing done CB8C5EB878248DCF0E1D4B215E247F81A7F25A76
  04-16 18:47:25.387 2453-2679/? E/Icing: Aborting indexing of corpus internal.3p:DigitalDocument
  04-16 18:47:25.388 2453-2679/? I/Icing: Indexing 1025AB1BD34441691C05DD1956DAC0055E9B9892 from com.google.android.apps.docs
  04-16 18:47:25.388 2453-2679/? I/Icing: Not enough disk space for indexing trimmable
  04-16 18:47:25.388 2453-2679/? I/Icing: Cannot sync trimmable corpus: no trimmable
  04-16 18:47:25.388 2453-2679/? I/Icing: Indexing done 1025AB1BD34441691C05DD1956DAC0055E9B9892
  04-16 18:47:25.388 2453-2679/? E/Icing: Aborting indexing of corpus internal.3p:PresentationDigitalDocument
  04-16 18:47:25.391 2453-2679/? I/Icing: Indexing 2823A4E8E883823DE65F5628FB978D4BAB6FAF3D from com.google.android.apps.docs
  04-16 18:47:25.391 2453-2679/? I/Icing: Not enough disk space for indexing trimmable
  04-16 18:47:25.391 2453-2679/? I/Icing: Cannot sync trimmable corpus: no trimmable
  04-16 18:47:25.391 2453-2679/? I/Icing: Indexing done 2823A4E8E883823DE65F5628FB978D4BAB6FAF3D
  04-16 18:47:25.391 2453-2679/? E/Icing: Aborting indexing of corpus internal.3p:SpreadsheetDigitalDocument
  04-16 18:47:25.393 2453-2679/? I/Icing: Indexing 32815EDB0F7643A5A6F997853ED4BC43CC823D2A from com.google.android.apps.docs
  04-16 18:47:25.394 2453-2679/? I/Icing: Not enough disk space for indexing trimmable
  04-16 18:47:25.394 2453-2679/? I/Icing: Cannot sync trimmable corpus: no trimmable
  04-16 18:47:25.394 2453-2679/? I/Icing: Indexing done 32815EDB0F7643A5A6F997853ED4BC43CC823D2A
  04-16 18:47:25.394 2453-2679/? E/Icing: Aborting indexing of corpus internal.3p:TextDigitalDocument
  04-16 18:48:44.116 1648-1990/? W/AlarmManager: Window length 3074457345618258602ms suspiciously long; limiting to 1 hour
  04-16 18:50:56.225 2426-4002/? I/PlayCommon: [160] com.google.android.play.b.h.e(263): Preparing logs for uploading
  04-16 18:50:56.226 2426-4002/? I/PlayCommon: [160] com.google.android.play.b.h.e(267): No file ready to send
Phantômaxx
  • 36,442
  • 21
  • 78
  • 108
Lado
  • 266
  • 2
  • 15
  • @Barns but I wrote `final Context contexting = DataBaseTask.this;` – Lado Apr 16 '18 at 16:44
  • 2
    Yet another... **No, you cannot initialize Activity derived class with operator `new` by yourself.** – Selvin Apr 16 '18 at 16:44
  • Sorry, overlooked it. But, what purpose does the `DataBaseTask` class serve (other than just a `AsyncTask`). It appears to have no UI associated with it had there is no `onCreate` method for creating a UI. Please state the problem more clearly and explain where `DataBaseTask ` is called and what your intentions are. – Barns Apr 16 '18 at 17:16
  • @Barns I have another class where I called it like this `DataBaseTask db = new DataBaseTask("SANDTOKEN", token);` and that's all – Lado Apr 16 '18 at 17:22
  • @Barns when this class `DataBaseTask` will work properly it will send info to server and from server I will watch this information in dashboard(stripe's website) – Lado Apr 16 '18 at 17:24
  • @Barns No, I have one, where I wrote credit cards information. After successful token generation I call this `DataBaseTask` how I said it above. For writing credit cards information I used Stripe API for Android. – Lado Apr 16 '18 at 17:44
  • Take a look at the solution I provided. In my example the class "DataBaseTask" extends `AsyncTask` instead of `Activity`! I added a `Listener` as a callback mechanism, which will present the result upon completion. Let me know if you need any help. – Barns Apr 16 '18 at 18:16
  • @Barns it works. Thanks – Lado Apr 16 '18 at 18:29

1 Answers1

0

Create a new file for the class "DataBaseTask" that extends the AsyncTask (not extends Activity) :

public class DataBaseTask extends AsyncTask<String, Void, String> {

    private static final String TAG = "DataBaseTask";

    // Just in case you want a ProgressDialog uncomment this and the associated code
    //private ProgressDialog pDialog;

    private DataBaseTaskListener mListener;

    Context mContext;
    String mCommand = "";
    Token mToken;


    public DataBaseTask(Context context, String command, Token token, DataBaseTaskListener listener){
        this.mContext = context;
        this.mCommand = command;
        this.mToken = token;
        this.mListener = listener;
    }


    @Override
    protected String doInBackground(String... params) {
        String result = "";
        try{
            // Put your code here!!
        }
        catch(Exception ex){
            Log.e(TAG, ex.getMessage());
        }
        return result;
    }


    @Override
    protected void onPostExecute(String result) {
        try{
            // In case you want a ProgressDialog
            //pDialog.dismiss();

            // Trigger the listener for the call back sending the result
            mListener.onCompletedSendData(result);

             Log.e(TAG, "onPostExecute result: " + mData);
        }
        catch(Exception ex){
            Log.e(TAG, ex.getMessage());
        }
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        // In case you want a ProgressDialog
        //pDialog = new ProgressDialog(context);
        //pDialog.setMessage("Sending Data...");
        //pDialog.setIndeterminate(false);
        //pDialog.setCancelable(false);
        //pDialog.show();
    }
}

You can either create a new java file and call it "DataBaseTaskListener" or add this to your "DataBaseTask" class. I usually just make a new file.

public interface DataBaseTaskListener {
    void onCompletedSendData(String result);
}

Now you can call the new "DataBaseTask" from anywhere. Here I have an example of using an onClick event to call the new "DataBaseTask" AsyncTask.

public void onClickDataBaseAsyncTask(View view){
    try{
        DataBaseTaskListener listener = new DataBaseTaskListener() {
            @Override
            public void onCompletedSendData(String result) {
                //Do what you need with the data
            }
        };
        DataBaseTask c = new DataBaseTask(YourCallingActivity.this, yourCommand, yourToken, listener);
        c.execute();
    }
    catch (Exception ex){
        Log.e(TAG, ex.getMessage());
    }
}
Barns
  • 4,640
  • 3
  • 12
  • 27