2017-03-10 41 views
-1

我对Android Dev相当陌生,我创建了一个Google表单并希望在我的应用中实现该表单,并且听说Square开源的开放源代码okhttp,您很可能知道OkHttp不能正常工作

所以,我创建了一个布局标签,给他们同样的ID和一切... 我创建了一个名为并插入所有代码的Java类,并没有任何错误。

(值得一提的,我使用导览活动,不知道这是否影响或不虽然)

所以执行和纠正一切后,有改正的,我跑的应用程序,但它只是没有做任何事情。它不会执行验证,也不会发送响应。

我会很感激,如果有人可以帮助我这个

我会再次离开这里

代码,谢谢。

package com.example.eduardobastos.testapp; 


import android.content.Context; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.text.TextUtils; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 

import com.squareup.okhttp.MediaType; 
import com.squareup.okhttp.OkHttpClient; 
import com.squareup.okhttp.Request; 
import com.squareup.okhttp.RequestBody; 
import com.squareup.okhttp.Response; 

import java.io.IOException; 
import java.io.UnsupportedEncodingException; 
import java.net.URLEncoder; 


public class Form extends AppCompatActivity { 

public static final MediaType FORM_DATA_TYPE 
     = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"); 
//URL derived from form URL 
public static final String URL="https://docs.google.com/forms/d/e/1FAIpQLSeZp9wjprZJ3OR2SkIHHsZE9yDBAVnC7mO8hPKSzwGuYhqmdw/formResponse"; 
//input element ids found from the live form page 
public static final String EMAIL_KEY="entry_943499687"; 
public static final String SUBJECT_KEY="entry_2058392291"; 
public static final String MESSAGE_KEY="entry_1420026128"; 

private Context context; 
private EditText emailEditText; 
private EditText subjectEditText; 
private EditText messageEditText; 

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

    //save the activity in a context variable to be used afterwards 
    context =this; 

    //Get references to UI elements in the layout 
    Button sendButton = (Button)findViewById(R.id.sendButton); 
    emailEditText = (EditText)findViewById(R.id.emailEditText); 
    subjectEditText = (EditText)findViewById(R.id.subjectEditText); 
    messageEditText = (EditText)findViewById(R.id.messageEditText); 

    sendButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      //Make sure all the fields are filled with values 
      if(TextUtils.isEmpty(emailEditText.getText().toString()) || 
        TextUtils.isEmpty(subjectEditText.getText().toString()) || 
        TextUtils.isEmpty(messageEditText.getText().toString())) 
      { 
       Toast.makeText(context,"All fields are mandatory.",Toast.LENGTH_LONG).show(); 
       return; 
      } 
      //Check if a valid email is entered 
      if(!android.util.Patterns.EMAIL_ADDRESS.matcher(emailEditText.getText().toString()).matches()) 
      { 
       Toast.makeText(context,"Please enter a valid email.",Toast.LENGTH_LONG).show(); 
       return; 
      } 

      //Create an object for PostDataTask AsyncTask 
      PostDataTask postDataTask = new PostDataTask(); 

      //execute asynctask 
      postDataTask.execute(URL,emailEditText.getText().toString(), 
        subjectEditText.getText().toString(), 
        messageEditText.getText().toString()); 
     } 
    }); 
} 



//AsyncTask to send data as a http POST request 
private class PostDataTask extends AsyncTask<String, Void, Boolean> { 

    @Override 
    protected Boolean doInBackground(String... contactData) { 
     Boolean result = true; 
     String url = contactData[0]; 
     String email = contactData[1]; 
     String subject = contactData[2]; 
     String message = contactData[3]; 
     String postBody=""; 

     try { 
      //all values must be URL encoded to make sure that special characters like & | ",etc. 
      //do not cause problems 
      postBody = EMAIL_KEY+"=" + URLEncoder.encode(email,"UTF-8") + 
        "&" + SUBJECT_KEY + "=" + URLEncoder.encode(subject,"UTF-8") + 
        "&" + MESSAGE_KEY + "=" + URLEncoder.encode(message,"UTF-8"); 
     } catch (UnsupportedEncodingException ex) { 
      result=false; 
     } 



     try{ 
      //Create OkHttpClient for sending request 
      OkHttpClient client = new OkHttpClient(); 
      //Create the request body with the help of Media Type 
      RequestBody body = RequestBody.create(FORM_DATA_TYPE, postBody); 
      Request request = new Request.Builder() 
        .url(url) 
        .post(body) 
        .build(); 
      //Send the request 
      Response response = client.newCall(request).execute(); 
     }catch (IOException exception){ 
      result=false; 
     } 
     return result; 
    } 

    @Override 
    protected void onPostExecute(Boolean result){ 
     //Print Success or failure message accordingly 
     Toast.makeText(context,result?"Message successfully sent!":"There was some error in sending message. Please try again after some time.",Toast.LENGTH_LONG).show(); 
    } 

} 

}

+0

你试过调试?它是否输入任务的doInBackground方法? –

+0

嗨Jav T.我会在4/5h尝试。我刚刚去睡觉。现在是早上六点半。你有没有注意到我应该检查的其他东西,或者错误/不好? –

+0

完全没有,请继续关注调试操作,我也可以给你一些关于使用该任务类的提示;) –

回答

0

刚刚进行了测试,工程就像一个魅力...

import android.content.Context; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.support.design.widget.FloatingActionButton; 
import android.support.design.widget.Snackbar; 
import android.support.v4.widget.TextViewCompat; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar; 
import android.view.View; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.widget.Toast; 

import java.io.IOException; 
import java.io.UnsupportedEncodingException; 
import java.net.URLEncoder; 

import butterknife.BindView; 
import butterknife.ButterKnife; 
import mx.com.iisi.staffing.R; 
import okhttp3.MediaType; 
import okhttp3.OkHttpClient; 
import okhttp3.Request; 
import okhttp3.RequestBody; 
import okhttp3.Response; 

public class MessageActivity extends AppCompatActivity { 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_message); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 
     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
    } 

    @Override 
    protected void onResume() { 
     super.onResume(); 
     new PostDataTask(this).execute("","[email protected]","Testing","Testing message"); 
    } 

    private class PostDataTask extends AsyncTask<String, Void, Boolean> { 

     public final MediaType FORM_DATA_TYPE 
       = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"); 
     //URL derived from form URL 
     public static final String URL="https://docs.google.com/forms/d/e/1FAIpQLSeZp9wjprZJ3OR2SkIHHsZE9yDBAVnC7mO8hPKSzwGuYhqmdw/formResponse"; 
     //input element ids found from the live form page 
     public static final String EMAIL_KEY="entry_943499687"; 
     public static final String SUBJECT_KEY="entry_2058392291"; 
     public static final String MESSAGE_KEY="entry_1420026128"; 
     private Context context; 

     public PostDataTask(Context context) 
     { 
      this.context = context; 
     } 

     @Override 
     protected Boolean doInBackground(String... contactData) { 
      Boolean result = true; 
      String url = contactData[0]; 
      String email = contactData[1]; 
      String subject = contactData[2]; 
      String message = contactData[3]; 
      String postBody=""; 

      try { 
       //all values must be URL encoded to make sure that special characters like & | ",etc. 
       //do not cause problems 
       postBody = EMAIL_KEY+"=" + URLEncoder.encode(email,"UTF-8") + 
         "&" + SUBJECT_KEY + "=" + URLEncoder.encode(subject,"UTF-8") + 
         "&" + MESSAGE_KEY + "=" + URLEncoder.encode(message,"UTF-8"); 
      } catch (UnsupportedEncodingException ex) { 
       result=false; 
      } 



      try{ 
       //Create OkHttpClient for sending request 
       OkHttpClient client = new OkHttpClient(); 
       //Create the request body with the help of Media Type 
       RequestBody body = RequestBody.create(FORM_DATA_TYPE, postBody); 
       Request request = new Request.Builder() 
         .url(URL) 
         .post(body) 
         .build(); 
       //Send the request 
       Response response = client.newCall(request).execute(); 
      }catch (IOException exception){ 
       result=false; 
      } 
      return result; 
     } 

     @Override 
     protected void onPostExecute(Boolean result){ 
      Toast.makeText(context,result?"Message successfully sent!":"There was some error in sending message. Please try again after some time.",Toast.LENGTH_LONG).show(); 
     } 

    } 
} 
+0

不能让它工作... –

+0

给我你的布局文件和病后的代码;) –

+0

我会在一小时内添加你好吗? –