无法在Android 4.0.4上获取互联网数据

时间:2013-02-10 03:48:25

标签: android json nullpointerexception android-4.0-ice-cream-sandwich null-pointer


我的Android开发应用程序存在问题。
我试图通过JSON Parser从Google Translate API获取数据。
该应用程序在仿真器(v 2.1)和T-Mobile移动平衡(v 2.3.5)上完美运行 问题发生在Android 4.0.4(设备ZTE BLADE III)。当我尝试获取数据时,它返回空指针(由try-catch块包围的NullPointerException)。

Manifest中有应用程序权限

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

我认为Manifest中的错误或设备上的设置配置(已经检查过互联网连接并与其他应用程序一起工作。浏览器也有效),因为该应用程序在旧版本中运行良好。
任何帮助,将不胜感激。提前谢谢。

我认为不需要 这是带有一个按钮和两个微调器的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();
    }   
}

2 个答案:

答案 0 :(得分:0)

也许您的问题是因为您没有使用AsyncTask来获取该数据。

答案 1 :(得分:0)

使用AsyncTask这里的链接http://steveliles.github.com/android_s_asynctask.html可能会帮助您解决问题