Я использую этот код для публикации данных в php —
package com.nas.cruzer;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.nas.cruzer.UserEditProfileActivity.UpdateInfo;
import com.nas.cruzer.util.JSONParser;
import com.nas.cruzer.util.UserInfo;
import com.nas.cruzer.util.Util;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.util.Log;
import android.view.MenuItem;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint("SetJavaScriptEnabled") public class payment extends Activity {
private static final String TAG = "payment.java";
private WebView webView;
JSONParser jparser=new JSONParser();
public static HashMap<String, String> pay;
public static final String payUrl = "http://fuelongo.com/ap2/fog/pay/PayUMoney_form.php";
String x,y,tot,fuel,mail,phone,responseServer;
TextView test;
Context con= payment.this;
@SuppressLint("JavascriptInterface") public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new PostDataAsyncTask().execute();
setContentView(R.layout.payment);
webView = (WebView) findViewById(R.id.pay);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");webView.loadUrl(payUrl);
//test=(TextView) findViewById(R.id.x);
}public class PostDataAsyncTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
// do stuff before posting data
}
@Override
protected String doInBackground(String... strings) {
try {
postText();// post a file} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String lenghtOfFile) {
// do stuff after posting data
}
}
// this will post our text data
private void postText(){
try{
// url where the data will be posted
Log.v(TAG, "postURL: " + payUrl);
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(payUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("firstname", "Mike"));
nameValuePairs.add(new BasicNameValuePair("lastname", "Dalisay"));
nameValuePairs.add(new BasicNameValuePair("email", "[email protected]"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v(TAG, "Response: " + responseStr);
// you can add an if statement here and do other actions based on the response
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}/** Show a toast from the web page */
}
}
Приведенный выше код после выполнения запроса в моем php получает желаемое значение и выполняет тост, но когда я пытаюсь установить текст в текстовое представление, он показывает исключение Null Pointer.
Любая помощь?
Это мой log cat out, «s» — это значение, которое я отправляю, а kitkat — значение, запрашиваемое из базы данных.
06-10 15:37:56.390: V/payment.java(28930): Response: Array
06-10 15:37:56.390: V/payment.java(28930): (
06-10 15:37:56.390: V/payment.java(28930): [firstname] => Mike
06-10 15:37:56.390: V/payment.java(28930): [lastname] => Dalisay
06-10 15:37:56.390: V/payment.java(28930): [email] => [email protected]
06-10 15:37:56.390: V/payment.java(28930): )
06-10 15:37:56.390: V/payment.java(28930): [email protected]<html>
06-10 15:37:56.390: V/payment.java(28930): <head>
06-10 15:37:56.390: V/payment.java(28930): <script>
06-10 15:37:56.390: V/payment.java(28930): var hash = '';
06-10 15:37:56.390: V/payment.java(28930): function submitPayuForm() {
06-10 15:37:56.390: V/payment.java(28930): if(hash == '') {
06-10 15:37:56.390: V/payment.java(28930): return;
06-10 15:37:56.390: V/payment.java(28930): }
06-10 15:37:56.390: V/payment.java(28930): var payuForm = document.forms.payuForm;
06-10 15:37:56.390: V/payment.java(28930): payuForm.submit();
06-10 15:37:56.390: V/payment.java(28930): }
06-10 15:37:56.390: V/payment.java(28930): </script>
06-10 15:37:56.390: V/payment.java(28930): </head>
06-10 15:37:56.390: V/payment.java(28930): <body onload="submitPayuForm()">
06-10 15:37:56.390: V/payment.java(28930): <h2>PayU Form</h2>
06-10 15:37:56.390: V/payment.java(28930): <br/>
06-10 15:37:56.390: V/payment.java(28930):
06-10 15:37:56.390: V/payment.java(28930): <span style="color:red">Please fill all mandatory fields.</span>
06-10 15:37:56.390: V/payment.java(28930): <br/>
06-10 15:37:56.390: V/payment.java(28930): <br/>
06-10 15:37:56.390: V/payment.java(28930): <form action="" method="post" name="payuForm">
06-10 15:37:56.390: V/payment.java(28930): <input type="hidden" name="key" value="JBZaLc" />
06-10 15:37:56.390: V/payment.java(28930): <input type="hidden" name="hash" value=""/>
06-10 15:37:56.390: V/payment.java(28930): <input type="hidden" name="txnid" value="61937a215af325da6a54" />
06-10 15:37:56.390: V/payment.java(28930): <table>
06-10 15:37:56.390: V/payment.java(28930): <tr>
06-10 15:37:56.390: V/payment.java(28930): <td><b>Mandatory Parameters</b></td>
06-10 15:37:56.390: V/payment.java(28930): </tr>
06-10 15:37:56.390: V/payment.java(28930): <tr>
06-10 15:37:56.390: V/payment.java(28930): <td>Amount: </td>
06-10 15:37:56.390: V/payment.java(28930): <td><input name="amount" value="" /></td>
06-10 15:37:56.390: V/payment.java(28930): <td>First Name: </td>
06-10 15:37:56.390: V/payment.java(28930): <td><input name="firstname" id="firstname" value="Mike" /></td>
06-10 15:37:56.390: V/payment.java(28930): </tr>
06-10 15:37:56.390: V/payment.java(28930): <tr>
06-10 15:37:56.390: V/payment.java(28930): <td>Email: </td>
06-10 15:37:56.390: V/payment.java(28930): <td><input name="email" id="email" value="[email protected]" /></td>
06-10 15:37:56.390: V/payment.java(28930): <td>Phone: </td>
06-10 15:37:56.390: V/payment.java(28930): <td><input name="phone" value="" /></td>
06-10 15:37:56.390: V/payment.java(28930): </tr>
06-10 15:37:56.390: V/payment.java(28930): <tr>
06-10 15:37:56.390: V/payment.java(28930): <td>Product Info: </td>
06-10 15:37:56.390: V/payment.java(28930): <td colspan="3"><textarea name="productinfo"></textarea></td>
06-10 15:37:56.390: V/payment.java(28930): </tr>
06-10 15:37:56.390: V/payment.java(28930): <tr>
06-10 15:37:56.390: V/payment.java(28930): <td>Success URI: </td>
06-10 15:37:56.390: V/payment.java(28930): <td colspan="3"><input name="surl" value="" size="64" /></td>
06-10 15:37:56.390: V/payment.java(28930): </tr>
06-10 15:37:56.390: V/payment.java(28930): <tr>
06-10 15:37:56.390: V/payment.java(28930): <td>Failure URI: </td>
06-10 15:37:56.390: V/payment.java(28930): <td colspan="3"><input name="furl" value="" size="64" /></td>
06-10 15:37:56.390: V/payment.java(28930): </tr>
06-10 15:37:56.390: V/payment.java(28930): <tr>
06-10 15:37:56.390: V/payment.java(28930): <td colspan="3"><input type="hidden" name="service_provider" value="payu_paisa" size="64" /></td>
06-10 15:37:56.390: V/payment.java(28930): </tr>
06-10 15:37:56.390: V/payment.java(28930): <tr>
06-10 15:37:56.390: V/payment.java(28930): <td><b>Optional Parameters</b></td>
06-10 15:37:56.390: V/payment.java(28930): </tr>
06-10 15:37:56.390: V/payment.java(28930): <tr>
06-10 15:37:56.390: V/payment.java(28930): <td>Last Name: </td>
06-10 15:37:56.390: V/payment.java(28930): <td><input name="lastname" id="lastname" value="Dalisay" /></td>
06-10 15:37:56.390: V/payment.java(28930): <td>Cancel URI: </td>
06-10 15:37:56.390: V/payment.java(28930): <td><input name="curl" value="" /></td>
06-10 15:37:56.390: V/payment.java(28930): </tr>
06-10 15:37:56.390: V/payment.java(28930): <tr>
06-10 15:37:56.390: V/payment.java(28930): <td>Address1: </td>
06-10 15:37:56.390: V/payment.java(28930): <td><input name="address1" value="" /></td>
06-10 15:37:56.390: V/payment.java(28930): <td>Address2: </td>
06-10 15:37:56.390: V/payment.java(28930): <td><input name="address2" value="" /></td>
06-10 15:37:56.390: V/payment.java(28930): </tr>
06-10 15:37:56.390: V/payment.java(28930): <tr>
06-10 15:37:56.390: V/payment.java(28930): <td>City: </td>
06-10 15:37:56.390: V/payment.java(28930): <td><input name="city" value="" /></td>
06-10 15:37:56.390: V/payment.java(28930): <td>State: </td>
06-10 15:37:56.390: V/payment.java(28930): <td><input name="state" value="" /></td>
06-10 15:37:56.390: V/payment.java(28930): </tr>
06-10 15:37:56.390: V/payment.java(28930): <tr>
06-10 15:37:56.390: V/payment.java(28930): <td>Country: </td>
06-10 15:37:56.390: V/payment.java(28930): <td><input name="country" value="" /></td>
06-10 15:37:56.390: V/payment.java(28930): <td>Zipcode: </td>
06-10 15:37:56.390: V/payment.java(28930): <td><input name="zipcode" value="" /></td>
06-10 15:37:56.390: V/payment.java(28930): </tr>
06-10 15:37:56.390: V/payment.java(28930): <tr>
06-10 15:37:56.390: V/payment.java(28930): <td>UDF1: </td>
06-10 15:37:56.390: V/payment.java(28930): <td><input name="udf1" value="" /></td>
06-10 15:37:56.390: V/payment.java(28930): <td>UDF2: </td>
06-10 15:37:56.390: V/payment.java(28930): <td><input name="udf2" value="" /></td>
06-10 15:37:56.390: V/payment.java(28930): </tr>
06-10 15:37:56.390: V/payment.java(28930): <tr>
06-10 15:37:56.390: V/payment.java(28930): <td>UDF3: </td>
06-10 15:37:56.390: V/payment.java(28930): <td><input name="udf3" value="" /></td>
06-10 15:37:56.390: V/payment.java(28930): <td>UDF4: </td>
06-10 15:37:56.390: V/payment.java(28930): <td><input name="udf4" value="" /></td>
06-10 15:37:56.390: V/payment.java(28930): </tr>
06-10 15:37:56.390: V/payment.java(28930): <tr>
06-10 15:37:56.390: V/payment.java(28930): <td>UDF5: </td>
06-10 15:37:56.390: V/payment.java(28930): <td><input name="udf5" value="" /></td>
06-10 15:37:56.390: V/payment.java(28930): <td>PG: </td>
06-10 15:37:56.390: V/payment.java(28930): <td><input name="pg" value="" /></td>
06-10 15:37:56.390: V/payment.java(28930): </tr>
06-10 15:37:56.390: V/payment.java(28930): <tr>
06-10 15:37:56.390: V/payment.java(28930): <td colspan="4"><input type="submit" value="Submit" /></td>
06-10 15:37:56.390: V/payment.java(28930): </tr>
06-10 15:37:56.390: V/payment.java(28930): </table>
06-10 15:37:56.390: V/payment.java(28930): </form>
06-10 15:37:56.390: V/payment.java(28930): </body>
06-10 15:37:56.390: V/payment.java(28930): </html>
Используйте AsynTask Class или Intent service для обработки изменений пользовательского интерфейса.
Исключение Null Pointer здесь не выдается из-за обратной строки здесь. Это потому, что тест равен нулю.
Это может быть из-за любой из следующих причин.
1. Убедитесь, что приведенный ниже фрагмент кода запущен перед вызовом test.setText
test = (TextView) findViewById (R.id.x)
Также убедитесь, что вы обновляете текстовое представление в главном потоке.
Первое, что не комментирует test=(TextView) findViewById(R.id.x);
и во-вторых, ваше призвание new PostDataAsyncTask().execute()
перед инициализацией textview,
поэтому сначала инициализируйте все переменные, затем загрузите остальную часть кода, выполните его и т. д.
Ваш код onCreate () должен быть таким
super.onCreate(savedInstanceState);
setContentView(R.layout.payment);
test=(TextView) findViewById(R.id.x);
webView = (WebView) findViewById(R.id.pay);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
webView.loadUrl(payUrl);
new PostDataAsyncTask().execute();
а потом test.setText("whatever you want");
а также проверьте, что id.x
доступно в payment layout
На данный момент проблема решена с помощью следующего кода:
public void postData() throws IOException, ClientProtocolException {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", x));
nameValuePairs.add(new BasicNameValuePair("mail", y));
nameValuePairs.add(new BasicNameValuePair("phone", phone));
nameValuePairs.add(new BasicNameValuePair("fuel", fuel));
nameValuePairs.add(new BasicNameValuePair("total", tot));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(payUrl);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String data = new BasicResponseHandler().handleResponse(response);
Log.e("data",data);
webView.loadData(data, "text/html", "utf-8");
}
Но кнопка в веб-представлении не работает
И может кто-нибудь объяснить мне, что делает этот код.