Android将图像从网站/ URL加载到图像视图会导致无法解决的空指针异常

时间:2014-04-11 19:10:14

标签: android image nullpointerexception

在详细介绍我遇到的麻烦之前,让我解释一下,我对Android开发很新,我将解释我想要实现的目标,到目前为止我在哪里以及我的问题遇到过。

我正在使用eclipse在4.0版本中开发一个Android应用程序,我想创建的是一个用户名和密码的登录页面,由用户输入然后由外部数据库检查以验证并显示一个警告,说明是否登录成功与否。如果成功,应用程序将加载一个新页面,其中包含从Web源获取的图像,例如:http://community.dur.ac.uk/cs.seg05/Wild/CameraImages/IMG_0364.JPG显示在页面上。此页面周围会显示更多信息以帮助用户对图像中的内容进行分类,一旦用户完成此图像,他们会按下一个按钮(我还没有把它放进去)并且会弹出一个新图像向上,过程重复。

到目前为止,我已经设法使登录页面正常工作,我可以使用文本和默认小部件等加载新的页面/活动,并使用android项目提供的默认图像。但是,当我尝试从URL访问图像并将其放在图像查看器中时,问题就出现了。

我已阅读并尝试了大约7-10种不同的实施方式(https://stackoverflow.com/questions/17495970/image-view-null-pointer-exception,https://stackoverflow.com/questions/4417552/null-pointer-exception-when-drawing-an-imageNull pointer exception when getting image from url to put in imageviewHow to load an ImageView by URL in Android?https://www.youtube.com/watch?v=KmYJBhz1gmk只是一些例子)但每一个单一的我试过在LogCat中返回以下错误消息然后崩溃应用程序,无论它是什么URL和图像是什么类型(jpg,png等):

Nb com.example.hello是包名(它就是我创建项目时的内容)

Fatal Exception: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.hello/com.example.hello.SecondActivity}: java.lang.NullPointerException
at android.app.Activity.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4340)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invokeNative(Method.java:511)
at com.android.internal.os.ZygotInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygotInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
(there is sometimes an extra error line here depending on what implementation I tried)
at com.example.hello.SecondActivity.onCreate(SecondActivity.java:58)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
... 11 more

现在我不认为互联网权限是一个问题,因为在遇到这个问题之前,我必须使用一些php文件进行一些互联网访问,而且它们都有效,而且我在android清单中也有用户权限你将在这篇文章中进一步了解的xml文件。另外,我不认为它是一个网址问题,因为我在我的浏览器中尝试了网址并且它们都很好。

所以我问的是:

是什么导致了这个问题?

解决问题的方法是什么(逐步是有用的)以及与我想要实现的内容一起使用的最佳实现? (一些代码会非常有用)

我是否需要在此处发布更多信息?

任何人都可以提供帮助

由于

P.S这是我在" SecondActivity"中的代码。在没有url的情况下工作(注意,一旦这个问题解决了,getImages方法适用于我将来需要的东西)

package com.example.hello;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.os.Build;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
public class SecondActivity extends Activity {
private String userId; //global variable as it will be used throughout this activity
private ArrayList <String> imageNames;
private int imageNumber=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
    Bundle data = getIntent().getExtras(); //obtains information passed from the previous activity
    userId= data.getString("userId"); //gets the user id from the main activity
    System.err.println("Received User  id " +userId);
    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }
    imageNames =getImages(userId); //gets all of the image names from the database
    System.err.println(imageNames);

    ImageView iv= (ImageView)findViewById(R.id.imageView1); //gets the image view
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.second, 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();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_second,
                container, false);
        return rootView;
    }
}


public ArrayList<String> getImages(String userid) {
    ArrayList<String> images= new ArrayList<String>();
    try {
        HttpClient httpclient= new DefaultHttpClient();
        URI website= new URI("https://community.dur.ac.uk/cs.seg05/androidapp/ImageAccess.php?userid="+userid);
        HttpGet request= new HttpGet();
        request.setURI(website);

        HttpResponse response = httpclient.execute(request);

        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb=new StringBuffer("");
        String l= "";
        String nl= System.getProperty("line.separator");

        while ((l = reader.readLine()) != null) { //converts the whole output into a string 
            sb.append(l+ nl);
    }
        reader.close();
        String result=sb.toString();
        //System.err.println(result);





            JSONArray jArray = new JSONArray(result);
            System.err.println(jArray);
            for(int i=0;i<jArray.length();i++){ //retrieves the JSon
                    JSONObject json_data = jArray.getJSONObject(i);
                    images.add(json_data.getString("File_Name"));



    }


        }
        catch (Exception e) {

        }


    return images;


}

}

这是包含imageview的xml,活动映射到:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.hello.SecondActivity$PlaceholderFragment" >

  <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="144dp" />

</RelativeLayout>

以下是我的Android清单的xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hello"
android:versionCode="1"
android:versionName="1.0" >

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="14" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.hello.MainActivity" //login activity
        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="com.example.hello.SecondActivity"
        android:label="@string/app_name" >
    </activity>
</application>

希望这是足够的信息。如果没有,请告诉我,我会发布

这是我尝试过的一个例子

Bitmap bm= getBitmapFromURL("http://community.dur.ac.uk/cs.seg05/Wild/CameraImages/1");
    ImageView iv= (ImageView)findViewById(R.id.imageView1); //gets the image view
    iv.setImageBitmap(bm); //this is line 58 in this example 

其中getBitmapFromURL是此方法

public static Bitmap getBitmapFromURL(String src) {
        try {
            java.net.URL url = new java.net.URL(src);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

2 个答案:

答案 0 :(得分:0)

at com.example.hello.SecondActivity.onCreate(SecondActivity.java:58)

说错误发生在SecondActivity.java的第58行。第58行在这里:

ImageView iv= (ImageView)findViewById(R.id.imageView1); //gets the image view
iv.setImageBitmap(bm); //this is line 58 in this example 

因此,iv似乎是null

ivnull,因为activity_second.xml不包含ID为imageView1

的ImageView

要修复此问题,您可以将所有代码移至Fragment课程,也可以将xml移至activity_main.xml

可能还值得再次查看Fragment文档http://developer.android.com/guide/components/fragments.html

答案 1 :(得分:0)

我的答案与您解决的问题无关。

但您可能希望查看AsyncTask来执行图像下载,而不是在UI线程中执行它们。

http://developer.android.com/reference/android/os/AsyncTask.html

Android开发者博客上还有一篇有趣的帖子:

http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html