【发布时间】:2020-08-31 07:43:02
【问题描述】:
我的 Android 应用已启动并运行(Main Activity) ,我使用了从互联网上显示的数据列表(也添加了),当我单击它进行下一个活动(PokeActivity)时,LogCat 中出现错误> as “java.net.MalformedURLException:尝试在空对象引用上调用虚拟方法'int java.lang.String.length()'”
PokeActivity里面的代码
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class PokemonActivity extends AppCompatActivity {
private TextView nameTextView;
private TextView numberTextView;
private TextView type1TextView;
private TextView type2TextView;
private String url;
private RequestQueue requestQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pokemon);
requestQueue= Volley.newRequestQueue(getApplicationContext());
String url = getIntent().getStringExtra("url");
nameTextView = findViewById(R.id.pokemon_name);
numberTextView= findViewById(R.id.pokemon_number);
type1TextView=findViewById(R.id.pokemon_type1);
type2TextView=findViewById(R.id.pokemon_type2);
load();
}
public void load (){
type1TextView.setText("");
type2TextView.setText("");
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
nameTextView.setText(response.getString("name"));
nameTextView.setText(String.format("#%3d",response.getInt("id")));
JSONArray typeEntries = response.getJSONArray("types");
for(int i = 0 ;i < typeEntries.length();i++){
JSONObject typeEntry = typeEntries.getJSONObject(i);
int slot = typeEntry.getInt("slot");
String type = typeEntry.getJSONObject("type").getString("name");
if(slot==1){
type1TextView.setText(type);
}else if(slot==2){
type2TextView.setText(type);
}
}
} catch (JSONException e) {
Log.e("cs50", "Pokemon Json error", e);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("cs50","pokemon details error", error);
}
});
requestQueue.add(request);
}
}```
【问题讨论】:
标签: android json nullpointerexception cs50