我为 Android 开发的应用程序有问题。
我试图通过 JSON Parser 从 Google Translate API 获取数据。
该应用程序在 Emulator (v 2.1) 和 T-Mobile Move Balance (v 2.3.5) 上完美运行该问题发生在 Android 4.0.4(设备 ZTE BLADE III)上。当我尝试获取数据时,它返回空指针( NullPointerException 被 try-catch 块包围)。
清单上有应用程序权限
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
我认为是设备上的清单或设置配置错误(已检查互联网连接并与其他应用程序一起使用。浏览器也可以),因为该应用程序在旧版本中运行良好。
任何帮助,将不胜感激。提前致谢。
我认为不需要
这是带有一个按钮和两个微调器的 Activity,按钮上有监听器
public class OptionsActivity extends Activity {
private String mSourceLanguage, mDestinationLanguage;
private Spinner sourceSpinner, destinationSpinner;
private static ArrayList<Language> languages;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_options);
sourceSpinner = (Spinner)findViewById(R.id.spinner1);
destinationSpinner = (Spinner)findViewById(R.id.spinner2);
updateSpinners();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_options, menu);
return true;
}
// isprakjanje na informacii na jazicite do ManuaInputActivity
public void submitLanguages(View v){
mSourceLanguage = sourceSpinner.getSelectedItem().toString();
mDestinationLanguage = destinationSpinner.getSelectedItem().toString();
String sourceCode = "", destCode = "";
sourceCode = getCode(mSourceLanguage);
destCode = getCode(mDestinationLanguage);
Intent intent = new Intent(this, ManualInputActivity.class);
Bundle spinnerBundle = new Bundle();
spinnerBundle.putString("sourceLanguage", mSourceLanguage + " ["+ sourceCode + "]");
spinnerBundle.putString("sourceCode", sourceCode);
spinnerBundle.putString("destinationLanguage", mDestinationLanguage + " [" + destCode + "]");
spinnerBundle.putString("destinationCode", getCode(mDestinationLanguage));
intent.putExtras(spinnerBundle);
setResult(RESULT_OK, intent);
super.finish();
}
// moze da mi treba pokasno za polnenje na spinner-ite
private ArrayAdapter<String> initializeSpinner(ArrayList<Language> lang){
ArrayList<String> entries = new ArrayList<String>();
for(Language l: lang){
entries.add(l.getLanguageName());
}
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,entries);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
return spinnerAdapter;
}
private void updateSpinners(){
GoogleRequest gr = new GoogleRequest();
try {
String result = gr.requestLanguages("en");
languages = gr.getLanguagesFromJSONObject(result);
sourceSpinner.setAdapter(initializeSpinner(languages));
destinationSpinner.setAdapter(initializeSpinner(languages));
} catch (NullPointerException e) {
// TODO: handle exception
Toast.makeText(this, "Empty spinners.. NO DATA...", Toast.LENGTH_SHORT).show();
}
}
private String getCode(String s){
String ss="xx";
for (Language l : languages){
if(l.getLanguageName().toString()==s)
ss = l.getLanguageCode().toString();
}
return ss;
}
}
和 GoogleRequest 类...
public class GoogleRequest {
private final String requestURL = "https://www.googleapis.com/language/translate/v2?key=";
private final String requestURLLang = "https://www.googleapis.com/language/translate/v2/languages?key=";
private final String requestKey = "**************";
private final String requestSrc = "&source=";
private final String requestDst = "&target=";
private final String requestTxt = "&q=";
public String requestLanguages(String target){
String request = requestURLLang + requestKey + requestDst + target;
try {
URL url = new URL(request);
URLConnection connection = url.openConnection();
connection.connect();
InputStreamReader inputStreamReader = new InputStreamReader( connection.getInputStream(), "UTF-8" );
BufferedReader in = new BufferedReader( inputStreamReader, 512 );
StringBuffer sb = new StringBuffer();
String line;
while ( ( line = in.readLine() ) != null ) {
sb.append( line );
}
in.close();
return sb.toString();
}
catch ( Exception e ) {
e.printStackTrace();
}
return null;
}
public String requestTranslation( String txt, String src, String dst ) {
String request = requestURL + requestKey + requestSrc + src + requestDst + dst + requestTxt;
try {
request += URLEncoder.encode( txt, "UTF-8" );
URL url = new URL(request);
URLConnection connection = url.openConnection();
connection.connect();
InputStreamReader inputStreamReader = new InputStreamReader( connection.getInputStream(), "UTF-8" );
BufferedReader in = new BufferedReader( inputStreamReader, 512 );
StringBuffer sb = new StringBuffer();
String line;
while ( ( line = in.readLine() ) != null ) {
sb.append( line );
}
in.close();
return sb.toString();
}
catch ( Exception e ) {
e.printStackTrace();
}
return null;
}
public String getTextFromJSONObject(String text){
try{
JSONObject mainObj = new JSONObject(text);
JSONObject data = mainObj.getJSONObject("data");
JSONArray translations = data.getJSONArray("translations");
String result = "";
for(int i=0; i <translations.length(); i++){
JSONObject translatedText = translations.getJSONObject(i);
result += translatedText.getString("translatedText");
}
return result;
}catch (JSONException e) {
// TODO: handle exception
Toast.makeText(null, "Parsing error!", Toast.LENGTH_SHORT).show();
return null;
}
}
public ArrayList<Language> getLanguagesFromJSONObject(String text){
ArrayList<Language> googleLanguages = new ArrayList<Language>();
try {
JSONObject mainObj = new JSONObject(text);
JSONObject data = mainObj.getJSONObject("data");
JSONArray languages = data.getJSONArray("languages");
for(int i=0; i<languages.length(); i++){
Language l = new Language();
JSONObject language = languages.getJSONObject(i);
l.setLanuguageCode(language.getString("language"));
l.setLanuguageName(language.getString("name"));
googleLanguages.add(l);
}
return googleLanguages;
} catch (JSONException e) {
Toast.makeText(null, "Parsing error!", Toast.LENGTH_SHORT).show();
return null;
}
}
public String printLista(ArrayList<Language> l){
String s="";
for(Language la: l){
s+= la.getLanguageName().toString() + " [" + la.getLanguageCode().toString() + "]";
}
return s;
}}
选项布局...
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".OptionsActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="0.98"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/label_choose_source"
android:textAppearance="?android:attr/textAppearanceSmall" />
<Spinner
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:prompt="@string/label_choose_source"
android:entries="@array/spinner1_entries"
android:layout_height="wrap_content" />
<android.support.v7.widget.Space
android:id="@+id/space1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/label_choose_destination"
android:textAppearance="?android:attr/textAppearanceSmall" />
<Spinner
android:id="@+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/spinner1_entries"
android:prompt="@string/label_choose_destination" />
</LinearLayout>
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="submitLanguages"
android:text="@string/button_submit_languages" />
和 LogCat:
02-10 06:01:49.941: E/AndroidRuntime(10653): FATAL EXCEPTION: main
02-10 06:01:49.941: E/AndroidRuntime(10653): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.textshottranslator/com.example.textshottranslator.OptionsActivity}: java.lang.NullPointerException
02-10 06:01:49.941: E/AndroidRuntime(10653): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1976)
02-10 06:01:49.941: E/AndroidRuntime(10653): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2001)
02-10 06:01:49.941: E/AndroidRuntime(10653): at android.app.ActivityThread.access$600(ActivityThread.java:130)
02-10 06:01:49.941: E/AndroidRuntime(10653): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1163)
02-10 06:01:49.941: E/AndroidRuntime(10653): at android.os.Handler.dispatchMessage(Handler.java:99)
02-10 06:01:49.941: E/AndroidRuntime(10653): at android.os.Looper.loop(Looper.java:137)
02-10 06:01:49.941: E/AndroidRuntime(10653): at android.app.ActivityThread.main(ActivityThread.java:4444)
02-10 06:01:49.941: E/AndroidRuntime(10653): at java.lang.reflect.Method.invokeNative(Native Method)
02-10 06:01:49.941: E/AndroidRuntime(10653): at java.lang.reflect.Method.invoke(Method.java:511)
02-10 06:01:49.941: E/AndroidRuntime(10653): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
02-10 06:01:49.941: E/AndroidRuntime(10653): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
02-10 06:01:49.941: E/AndroidRuntime(10653): at dalvik.system.NativeStart.main(Native Method)
02-10 06:01:49.941: E/AndroidRuntime(10653): Caused by: java.lang.NullPointerException
02-10 06:01:49.941: E/AndroidRuntime(10653): at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
02-10 06:01:49.941: E/AndroidRuntime(10653): at org.json.JSONTokener.nextValue(JSONTokener.java:94)
02-10 06:01:49.941: E/AndroidRuntime(10653): at org.json.JSONObject.(JSONObject.java:154)
02-10 06:01:49.941: E/AndroidRuntime(10653): at org.json.JSONObject.(JSONObject.java:171)
02-10 06:01:49.941: E/AndroidRuntime(10653): at com.example.textshottranslator.GoogleRequest.getLanguagesFromJSONObject(GoogleRequest.java:99)
02-10 06:01:49.941: E/AndroidRuntime(10653): at com.example.textshottranslator.OptionsActivity.updateSpinners(OptionsActivity.java:76)
02-10 06:01:49.941: E/AndroidRuntime(10653): at com.example.textshottranslator.OptionsActivity.onCreate(OptionsActivity.java:27)
02-10 06:01:49.941: E/AndroidRuntime(10653): at android.app.Activity.performCreate(Activity.java:4494)
02-10 06:01:49.941: E/AndroidRuntime(10653): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
02-10 06:01:49.941: E/AndroidRuntime(10653): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1940)
02-10 06:01:49.941: E/AndroidRuntime(10653): ... 11 more
当 updateSpinners() 方法被修改为这样时,LogCat 看起来像这样:
private void updateSpinners(){
GoogleRequest gr = new GoogleRequest();
String result = gr.requestLanguages("en");
languages = gr.getLanguagesFromJSONObject(result);
sourceSpinner.setAdapter(initializeSpinner(languages));
destinationSpinner.setAdapter(initializeSpinner(languages));
try {
} catch (NullPointerException e) {
// TODO: handle exception
Toast.makeText(this, "THIS IS IRRELEVANT NOW ...", Toast.LENGTH_SHORT).show();
}
}