首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android将图像从网站/URL加载到图像视图中,会导致无法解决的空指针异常

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

Stack Overflow用户
提问于 2014-04-11 19:10:14
回答 2查看 678关注 0票数 1

在我详细介绍我遇到的麻烦之前,让我解释一下,我对android开发非常陌生,我将解释我正在努力实现的目标,我目前所处的位置,以及我遇到的问题。

我正在使用eclipse开发4.0版的android应用程序,我想要创建的是一个用户名和密码的登录页面,用户输入这个用户名和密码,然后由外部数据库检查,以验证和显示一个警报,说明登录是否成功。如果成功,应用程序将加载一个新页面,其中包含从web源获取的图像,如:显示在页面上的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是包名(它正是我创建项目时的名称)

代码语言:javascript
复制
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

现在,我不认为Internet权限是一个问题,因为在遇到这个问题之前,我必须对一些php文件进行一些internet访问,它们都可以工作,而且我在android清单xml文件中也有用户权限,您将在本文中进一步看到。此外,我不认为这是一个url问题,因为我已经尝试了url's在我的浏览器,他们都很好。

我想问的是:

是什么导致了这个问题?

解决这个问题的方法是什么(一步一步的有用)和我所描述的目标的最佳实现?(一些代码将非常有用)

我还需要在这里发布更多信息吗?

有人能帮忙吗?

谢谢

这里是我在我的"SecondActivity“中的代码,它不需要url内容就能工作(注意,一旦这个问题解决了,getImages方法可以很好地工作在我将来需要的东西上)

代码语言:javascript
复制
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;


}

}

下面是包含活动映射到的包含图像视图的xml:

代码语言:javascript
复制
<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:

代码语言:javascript
复制
<?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>

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

下面是我尝试过的一个例子

代码语言:javascript
复制
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是此方法。

代码语言:javascript
复制
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;
        }

    }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-04-11 19:34:13

代码语言:javascript
复制
at com.example.hello.SecondActivity.onCreate(SecondActivity.java:58)

说错误在SecondActivity.java的第58行。第58行在此:

代码语言:javascript
复制
ImageView iv= (ImageView)findViewById(R.id.imageView1); //gets the image view
iv.setImageBitmap(bm); //this is line 58 in this example 

所以,看起来ivnull

ivnull,因为activity_second.xml不包含带有id imageView1的ImageView。

要修复,可以将所有代码移动到Fragment类中,也可以将xml移动到activity_main.xml中。

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

票数 0
EN

Stack Overflow用户

发布于 2014-04-11 19:45:40

我的回答与你已经解决的问题无关。

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

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

android开发者博客上也有一篇有趣的文章:

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23020774

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档