我有一个Android应用程序,它包含两个类JSONTransmitter类和MainActivity类,此应用程序的目标是发布并从php文件获取响应并在小部件上显示此响应。
我对MainActivity类的onResponse方法有一个小问题 - 当我使用button.setText(“”)时它不起作用,如果它不起作用!
JSONTransmitter类
public class JSONTransmitter extends AsyncTask<JSONObject, Void, String>
{
HttpResponse response;
String url = "http://192.168.1.13:89/Derdeery/b.php";
private AsyncCallback asyncCallback;
public static interface AsyncCallback {
void onResponse(String res);
}
public JSONTransmitter(Context context)
{
// attach the callback to any context
asyncCallback = (AsyncCallback) context;
}
protected String doInBackground(JSONObject... data) {
JSONObject json = data[0];
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
JSONObject jsonResponse = null;
HttpPost post = new HttpPost(url);
// initialize a return string
String resFromServer = "";
try {
StringEntity se = new StringEntity("json="+json.toString());
post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setEntity(se);
HttpResponse response;
response = client.execute(post);
// when you can get the json, you modify the return string
resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
Log.i("Response from server", resFromServer);
}
catch (Exception e)
{ e.printStackTrace();}
// now you can return a string
return resFromServer;
}
MainActivity类
public class MainActivity extends Activity implements JSONTransmitter.AsyncCallback {
private Button b ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button)findViewById(R.id.button1) ;
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
mymethod() ;
}
});
}
public void mymethod()
{
try {
TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String mPhoneNumber = tm.getLine1Number();
JSONObject toSend = new JSONObject();
toSend.put("msg", mPhoneNumber );
new JSONTransmitter(this).execute(new JSONObject[] {toSend});
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onResponse(String res)
{
// TODO Auto-generated method stub
Log.v("From_MainActivity", "AsyncTask returns this: "+res);
b.setText(res);
}
}
xml文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Button" />
</RelativeLayout>
将JSONTransmitter类更新为以下
public class JSONTransmitter extends AsyncTask<JSONObject, Void, String> {
HttpResponse response;
String url = "http://192.168.1.20:89/Derdeery/b.php";
private AsyncCallback asyncCallback;
public static interface AsyncCallback {
void onResponse(String res);
}
public JSONTransmitter(Context context)
{
// attach the callback to any context
asyncCallback = (AsyncCallback) context;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
asyncCallback.onResponse(result);
}
protected String doInBackground(JSONObject... data) {
JSONObject json = data[0];
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
JSONObject jsonResponse = null;
HttpPost post = new HttpPost(url);
// initialize a return string
String resFromServer = "";
try {
StringEntity se = new StringEntity("json="+json.toString());
post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setEntity(se);
HttpResponse response;
response = client.execute(post);
// when you can get the json, you modify the return string
resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
Log.i("Response from server", resFromServer);
}
catch (Exception e)
{ e.printStackTrace();}
// now you can return a string
return resFromServer;
}
我的应用程序崩溃,我收到此日志错误
01-18 06:30:07.721: E/AndroidRuntime(810): FATAL EXCEPTION: main
01-18 06:30:07.721: E/AndroidRuntime(810): java.lang.NullPointerException
01-18 06:30:07.721: E/AndroidRuntime(810): at com.coffeecodes.coffecodesdoodle.MainActivity.onResponse(MainActivity.java:66)
01-18 06:30:07.721: E/AndroidRuntime(810): at com.coffeecodes.coffecodesdoodle.JSONTransmitter.onPostExecute(JSONTransmitter.java:48)
01-18 06:30:07.721: E/AndroidRuntime(810): at com.coffeecodes.coffecodesdoodle.JSONTransmitter.onPostExecute(JSONTransmitter.java:1)
01-18 06:30:07.721: E/AndroidRuntime(810): at android.os.AsyncTask.finish(AsyncTask.java:631)
01-18 06:30:07.721: E/AndroidRuntime(810): at android.os.AsyncTask.access$600(AsyncTask.java:177)
01-18 06:30:07.721: E/AndroidRuntime(810): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
01-18 06:30:07.721: E/AndroidRuntime(810): at android.os.Handler.dispatchMessage(Handler.java:99)
01-18 06:30:07.721: E/AndroidRuntime(810): at android.os.Looper.loop(Looper.java:137)
01-18 06:30:07.721: E/AndroidRuntime(810): at android.app.ActivityThread.main(ActivityThread.java:5039)
01-18 06:30:07.721: E/AndroidRuntime(810): at java.lang.reflect.Method.invokeNative(Native Method)
01-18 06:30:07.721: E/AndroidRuntime(810): at java.lang.reflect.Method.invoke(Method.java:511)
01-18 06:30:07.721: E/AndroidRuntime(810): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-18 06:30:07.721: E/AndroidRuntime(810): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-18 06:30:07.721: E/AndroidRuntime(810): at dalvik.system.NativeStart.main(Native Method)
01-18 06:30:12.950: I/Process(810): Sending signal. PID: 810 SIG: 9
答案 0 :(得分:0)
MainActivity类的onResponse方法 - 当我使用button.setText(“”)时 它不起作用
要使其工作,请致电asyncCallback.onResponse()
中的onPostExecute
:
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
asyncCallback.onResponse(result);
}
覆盖onPostExecute
中的JSONTransmitter
并将result
字符串作为参数传递给onResponse
方法。