我一直在尝试使用volley连接并解析下面发布的活动中的JSON数据,但每次应用程序强制关闭时。 urlJsonObj的值是正确的,因为它在我从浏览器调用它时显示数据。我在哪里做错了?
package gsie.bizlink;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import android.app.ProgressDialog;
import android.os.AsyncTask;
public class CinteretsActivity extends ActionBarActivity implements View.OnClickListener {
private String prenom;
private String nom;
private String telephone1;
private String telephone2;
private String telephone3;
private String email;
private TextView myentries;
private static final String urlJsonObj ="http://www.pmsgroom.net/bizlink/CinteretsServlet";
private ArrayList<Cinteret> cinteretsList=new ArrayList<Cinteret>();
private CinteretsAdapter cinteretsadapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cinterets);
//myentries=(TextView) findViewById(R.id.textView);
Intent in=getIntent();
prenom=in.getStringExtra("prenom");
nom=in.getStringExtra("nom");
telephone1=in.getStringExtra("telephone1");
telephone2=in.getStringExtra("telephone2");
telephone3=in.getStringExtra("telephone3");
email=in.getStringExtra("email");
//myentries.setText(prenom+"\n"+nom+"\n"+telephone1+"\n"+telephone2+"\n"+telephone3+"\n"+email);
//new JSONParse().execute();
//cinteretsList=getList();
/*
AsyncHttpClient client = new AsyncHttpClient();
client.get(urlJsonObj,
new JsonHttpResponseHandler() {
@Override
public void onSuccess(JSONObject jsonObject) {
try {
JSONArray jarray = jsonObject.getJSONArray("cinterets");
String cinteretiden = "";
String cinterettext = "";
for (int i = 0; i < jarray.length(); i++) {
JSONObject cinteret = jarray.getJSONObject(i);
cinteretiden = cinteret.getString("cinteretid");
cinterettext = cinteret.getString("cinterettxt");
Cinteret cint = new Cinteret();
cint.setId(cinteretiden);
cint.setText(cinterettext);
cinteretsList.add(cint);
}
} catch (JSONException e) {
Log.d("jsonerror", "Error: " + e);
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(int statusCode, Throwable throwable, JSONObject error) {
Toast.makeText(getApplicationContext(), "Error: " + statusCode + " " + throwable.getMessage(), Toast.LENGTH_LONG).show();
Log.e("bizlink android", statusCode + " " + throwable.toString());
}
});
*/
//volley commence ici
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
urlJsonObj, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("reponse", response.toString());
try {
JSONArray jarray=response.getJSONArray("cinterets");
String cinteretiden="";
String cinterettext="";
for(int i=0;i<jarray.length();i++){
JSONObject cinteret=jarray.getJSONObject(i);
cinteretiden = cinteret.getString("cinteretid");
cinterettext=cinteret.getString("cinterettxt");
Cinteret cint=new Cinteret();
cint.setId(cinteretiden);
cint.setText(cinterettext);
cinteretsList.add(cint);
}
} catch (JSONException e) {
Log.d("jsonerror", "Error: " + e);
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("MainActivity", "Error: " + error);
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(5000,5,1f));
AppController.getInstance().addToRequestQueue(jsonObjReq);
//volley prend fin ici
/*
if(cinteretsList==null || cinteretsList.isEmpty()) {
Toast.makeText(getApplicationContext(),
"Liste centres d'interet est vide!",
Toast.LENGTH_LONG).show();
Log.d("reponse", "dedans");
Cinteret ct=new Cinteret();
ct.setId("1");
ct.setText("immobilier");
cinteretsList.add(ct);
Cinteret ct2=new Cinteret();
ct2.setId("2");
ct2.setText("locations");
cinteretsList.add(ct2);
}
*/
ListView listview = (ListView) findViewById(R.id.listView);
cinteretsadapter = new CinteretsAdapter(this, cinteretsList);
listview.setAdapter(cinteretsadapter);
Button valid=(Button) findViewById(R.id.finirbtn);
valid.setOnClickListener(this);
}
/*public ArrayList<Cinteret> getList(){
final ArrayList<Cinteret> ci=new ArrayList<Cinteret>();
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
urlJsonObj, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("reponse", response.toString());
try {
JSONArray jarray=response.getJSONArray("cinterets");
String cinteretiden="";
String cinterettext="";
for(int i=0;i<jarray.length();i++){
JSONObject cinteret=jarray.getJSONObject(i);
cinteretiden = cinteret.getString("cinteretid");
cinterettext=cinteret.getString("cinterettxt");
Cinteret cint=new Cinteret();
cint.setId(cinteretiden);
cint.setText(cinterettext);
ci.add(cint);
}
} catch (JSONException e) {
Log.d("jsonerror", "Error: " + e);
Toast.makeText(getApplicationContext(),
"Error: " + e.toString(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("MainActivity", "Error: " + error);
Toast.makeText(getApplicationContext(),
error.toString(), Toast.LENGTH_SHORT).show();
}
});
//AppController.getInstance().addToRequestQueue(jsonObjReq);
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(50000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonObjReq);
if(ci.size()==0 || ci==null){
Log.d("reponse", "dedans");
Cinteret ct=new Cinteret();
ct.setId("1");
ct.setText("immobilier");
ci.add(ct);
Cinteret ct2=new Cinteret();
ct2.setId("2");
ct2.setText("locations");
ci.add(ct2);
}
return ci;
}*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_cinterets, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
ArrayList<String> cinteretTextList=cinteretsadapter.getSelectedString();
ArrayList<String> cinteretIdList=cinteretsadapter.getSelectedId();
String cinteretTextStr="";
for (int i=0;i<cinteretTextList.size();i++){
cinteretTextStr=cinteretTextStr+cinteretTextList.get(i)+"\n";
}
Intent in=new Intent(this,ConfirmInscriptionActivity.class);
in.putExtra("prenom",prenom);
in.putExtra("nom", nom);
in.putExtra("telephone1", telephone1);
in.putExtra("telephone2",telephone2);
in.putExtra("telephone3",telephone3);
in.putExtra("email",email);
in.putExtra("cinterets",cinteretTextStr);
startActivity(in);
}
/*/debut paste
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CinteretsActivity.this);
pDialog.setMessage("Chargement ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(urlJsonObj);
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
JSONArray jarray=json.getJSONArray("cinterets");
String cinteretiden="";
String cinterettext="";
for(int i=0;i<jarray.length();i++){
JSONObject cinteret=jarray.getJSONObject(i);
cinteretiden = cinteret.getString("cinteretid");
cinterettext=cinteret.getString("cinterettxt");
Cinteret cint=new Cinteret();
cint.setId(cinteretiden);
cint.setText(cinterettext);
cinteretsList.add(cint);
}
} catch (JSONException e) {
Log.d("jsonerror", "Error: " + e);
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}
end paste*/
}
我的appController.java是:
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
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 <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
06-30 17:03:42.996 20691-20715/gsie.bizlink I/SurfaceTextureClient﹕ [STC::queueBuffer] (this:0x52f520e8) fps:2.10, dur:1428.35, max:497.07, min:434.57
06-30 17:03:42.997 144-14142/? I/BufferQueue﹕ [gsie.bizlink/gsie.bizlink.ContactsActivity](this:0x41b41a80,api:1) [queue] fps:2.10, dur:1428.42, max:497.07, min:434.69
06-30 17:03:43.006 144-234/? I/BufferQueue﹕ [gsie.bizlink/gsie.bizlink.ContactsActivity](this:0x41b41a80,api:1) [release] fps:2.10, dur:1428.57, max:496.91, min:434.77
06-30 17:03:43.172 517-1530/? I/ActivityManager﹕ START u0 {cmp=gsie.bizlink/.CinteretsActivity (has extras)} from pid 20691
06-30 17:03:43.222 517-534/? I/WindowManager﹕ Losing focus: Window{4212d2d8 u0 gsie.bizlink/gsie.bizlink.ContactsActivity}
06-30 17:03:43.329 20691-20691/gsie.bizlink D/AbsListView﹕ checkAbsListViewlLogProperty get invalid command
06-30 17:03:43.337 20691-20691/gsie.bizlink D/AndroidRuntime﹕ Shutting down VM
06-30 17:03:43.337 20691-20691/gsie.bizlink W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40d4b9a8)
06-30 17:03:43.344 20691-20691/gsie.bizlink E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{gsie.bizlink/gsie.bizlink.CinteretsActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2372)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424)
at android.app.ActivityThread.access$600(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5400)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:837)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at gsie.bizlink.CinteretsActivity.onCreate(CinteretsActivity.java:149)
at android.app.Activity.performCreate(Activity.java:5122)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2336)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424)
at android.app.ActivityThread.access$600(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5400)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:837)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:604)
at dalvik.system.NativeStart.main(Native Method)
06-30 17:03:43.354 517-783/? W/ActivityManager﹕ Force finishing activity gsie.bizlink/.CinteretsActivity
06-30 17:03:43.356 517-783/? W/ActivityManager﹕ Force finishing activity gsie.bizlink/.ContactsActivity
06-30 17:03:43.436 517-534/? I/WindowManager﹕ Gaining focus: Window{42218480 u0 Application Error: gsie.bizlink}
06-30 17:03:43.459 144-234/? I/BufferQueue﹕ [Application Error: gsie.bizlink](this:0x41b25008,api:0) setConsumerName: Application Error: gsie.bizlink
06-30 17:03:43.470 517-21594/? D/AES﹕ process : gsie.bizlink
06-30 17:03:43.470 517-21594/? D/AES﹕ module : gsie.bizlink v1 (1.0)
06-30 17:03:43.471 144-234/? I/BufferQueue﹕ [Application Error: gsie.bizlink](this:0x41b25008,api:0) setDefaultBufferSize: w=480, h=190
06-30 17:03:43.475 517-21594/? D/AEE/LIBAEE﹕ shell: raise_exp(2, 20691, -1361051648, gsie.bizlink, 0x0x5f14cae0, 0x0x0)
06-30 17:03:43.479 144-12221/? I/BufferQueue﹕ [Application Error: gsie.bizlink](this:0x41b25008,api:0) connect: api=2
06-30 17:03:43.479 144-12221/? I/BufferQueue﹕ [Application Error: gsie.bizlink](this:0x41b25008,api:2) setSynchronousMode: enabled=1
06-30 17:03:43.479 144-12932/? I/BufferQueue﹕ [Application Error: gsie.bizlink](this:0x41b25008,api:2) new GraphicBuffer needed
06-30 17:03:43.503 144-234/? I/SurfaceTexture﹕ [Application Error: gsie.bizlink](this:0x417f7798,api:2) [void* android::SurfaceTexture::createImage(EGLDisplay, const android::sp<android::GraphicBuffer>&)]
06-30 17:03:43.856 517-532/? W/ActivityManager﹕ Activity pause timeout for ActivityRecord{422b2d48 u0 gsie.bizlink/.CinteretsActivity}
06-30 17:03:49.201 144-543/? I/BufferQueue﹕ [Application Error: gsie.bizlink](this:0x41b25008,api:2) new GraphicBuffer needed
06-30 17:03:49.210 144-22775/? I/BufferQueue﹕ [Application Error: gsie.bizlink](this:0x41b25008,api:2) [queue] fps:0.17, dur:5717.39, max:5717.39, min:5717.39
06-30 17:03:49.217 144-234/? I/SurfaceTexture﹕ [Application Error: gsie.bizlink](this:0x417f7798,api:2) [void* android::SurfaceTexture::createImage(EGLDisplay, const android::sp<android::GraphicBuffer>&)]
06-30 17:03:49.217 144-14673/? I/BufferQueue﹕ [Application Error: gsie.bizlink](this:0x41b25008,api:2) new GraphicBuffer needed
06-30 17:03:49.232 144-234/? I/SurfaceTexture﹕ [Application Error: gsie.bizlink](this:0x417f7798,api:2) [void* android::SurfaceTexture::createImage(EGLDisplay, const android::sp<android::GraphicBuffer>&)]
06-30 17:03:53.222 517-532/? W/ActivityManager﹕ Activity idle timeout for ActivityRecord{422b2d48 u0 gsie.bizlink/.CinteretsActivity}
06-30 17:03:53.859 517-532/? W/ActivityManager﹕ Activity idle timeout for ActivityRecord{421fd170 u0 gsie.bizlink/.IdentificationActivity}
06-30 17:04:03.226 517-532/? W/ActivityManager﹕ Activity destroy timeout for ActivityRecord{42551e40 u0 gsie.bizlink/.ContactsActivity}
06-30 17:04:03.229 517-532/? W/ActivityManager﹕ Activity destroy timeout for ActivityRecord{422b2d48 u0 gsie.bizlink/.CinteretsActivity}
我的清单文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="gsie.bizlink" >
<uses-sdk
android:targetSdkVersion="22"
android:minSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".AppController"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".IdentificationActivity"
android:label="@string/title_activity_identification" >
</activity>
<activity
android:name=".ContactsActivity"
android:label="@string/title_activity_contacts" >
</activity>
<activity
android:name=".CinteretsActivity"
android:label="@string/title_activity_cinterets" >
</activity>
<activity
android:name=".ConfirmInscriptionActivity"
android:label="@string/title_activity_confirm_inscription" >
</activity>
</application>
</manifest>
答案 0 :(得分:2)
我可以看到您的代码,您忘记初始化cinteretsList
。因此,您必须在for
:
ArrayList<Cinteret> cinteretsList = new ArrayList<Cinteret>();
答案 1 :(得分:2)
尝试在Manifest.xml中添加AppController
<manifest ....
<application
android:name=".AppController"
android:allowBackup="true"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
...
</activity>
</application>
//permissions
</manifest>
答案 2 :(得分:2)