0


開発したAndroid用アプリに問題があります。
JSONパーサーを介してGoogle翻訳APIからデータを取得しようとしています。
このアプリケーションは、エミュレーター(v 2.1)およびT-Mobile Move Balance(v 2.3.5)で完全に動作します。問題はAndroid 4.0.4(デバイスZTE BLADE III)で発生します。データを取得しようとすると、nullポインター(try-catchブロックで囲まれたNullPointerException)が返されます。

マニフェストにはアプリの許可があります

 <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"/>

古いバージョンではアプリが正常に動作するため、マニフェストまたはデバイスの設定構成にエラーがあると思います(インターネット接続がすでに確認されており、他のアプリで動作します。ブラウザーも動作します)。
どんな助けでもいただければ幸いです。前もって感謝します。

必要ないと思いました
ボタンが1つとスピナーが2つあり、ボタンにリスナーがいるアクティビティです。

  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();
    }   
}
4

2 に答える 2

0

おそらくあなたの問題は、AsyncTaskそのデータを取得するためにを使用していないためです。

于 2013-02-10T04:30:53.133 に答える
0

AsyncTaskを使用してくださいここにリンクがありますhttp://steveliles.github.com/android_s_asynctask.htmlこれはあなたがあなたの問題を解決するのを助けることができるかもしれません

于 2013-02-10T06:16:34.043 に答える