简体   繁体   English

Android联网简单应用

[英]Android networking simple app

App works(api 23 tested also kitkat tested), but nothing shows, it should show picture(download it and put it in view). 应用程序可以正常工作(经过api 23测试,也经过kitkat测试),但是没有任何显示,应该显示图片(下载并显示)。 Since I am not getting any error, I am lost. 由于我没有收到任何错误,所以我迷路了。 I am looking from android beginner book for code, and they suggest apps to be tested on 4.0(icecream) but there is no recommended build in android studio for that version. 我正在从android初学者的书中寻找代码,他们建议在4.0(icecream)上测试应用程序,但是在该版本的android studio中没有推荐的构建。 Is it not working because of some change in how android works with HTTP and networking in latest APIs? 由于Android在最新API中使用HTTP和联网的方式发生了一些变化,因此无法正常工作吗?

public class NetworkingActivity extends Activity {

ImageView img;

private InputStream OpenHttpConnection(String urlString)
        throws IOException
{
    InputStream in = null;
    int response = -1;

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();

    if (!(conn instanceof HttpURLConnection))
        throw new IOException("Not an HTTP connection");
    try{
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();
        response = httpConn.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();
        }
    }
    catch (Exception ex)
    {
        Log.d("Networking", ex.getLocalizedMessage());
        throw new IOException("Error connecting");
    }
    return in;
}

private Bitmap DownloadImage(String URL)
{
    Bitmap bitmap = null;
    InputStream in = null;
    try {
        in = OpenHttpConnection(URL);
        bitmap = BitmapFactory.decodeStream(in);
        in.close();
    } catch (IOException e1) {
        Log.d("NetworkingActivity", e1.getLocalizedMessage());
    }
    return bitmap;
}

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    protected Bitmap doInBackground(String... urls) {
        return DownloadImage(urls[0]);
    }

    protected void onPostExecute(Bitmap result) {
        ImageView img = (ImageView) findViewById(R.id.img);
        img.setImageBitmap(result);
    }
}

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new DownloadImageTask().execute("http://www.mayoff.com/5-01cablecarDCP01934.jpg");

}
}

Here is logcat: 这是logcat:

日志猫

AndroidManifest.xml file: AndroidManifest.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="metropolitan.com.desetopredavanjeprotokoli10">

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

MainActivity class: MainActivity类:

package metropolitan.com.desetopredavanjeprotokoli10;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
}

Here you go: 干得好:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Smor"
    android:layout_gravity="center"/>

<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/img"
    android:layout_gravity="center"/>
</RelativeLayout>

Since you are beginer I suggest your learn how to use framework There a lot of benefit using framework if not you will need to implement some complex code for handling such as caching,resizing,avoiding memory crash,handling for almost all API which you are facing etc. 因为您是初学者,所以我建议您学习如何使用框架。如果没有框架,使用框架会有很多好处,您将需要实现一些复杂的代码来进行处理,例如缓存,调整大小,避免内存崩溃,几乎要处理的所有API的处理等等

For image download i suggest 对于图像下载,我建议

Picasso (which i suggest most) 毕加索 (我建议最多)

Glide 滑行

For normal Http request 对于普通的Http请求

Volley 凌空抽射

You can us Volley to download image as well. 您也可以使用Volley下载图像。 When you start learning it is kind a hard to understand but after u really get understading I promise you will not wan to use regular HTTPURLConnection to handle any HTTP Request 当您开始学习时,很难理解,但是在您真正了解之后,我保证您不会希望使用常规的HTTPURLConnection来处理任何HTTP请求

If you need upload with progress please let me know I will give add the code as well although it is much complicated. 如果您需要上传进度,请告诉我,尽管它非常复杂,但我也会提供代码。

Edited: 编辑:

So far I have been test out your code it work perfectly fine.I would like to add it for you. 到目前为止,我已经测试过您的代码,它可以很好地工作,我想为您添加它。

MainActivity 主要活动

    ImageView img;

    private InputStream OpenHttpConnection(String urlString)
            throws IOException
    {
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection))
            throw new IOException("Not an HTTP connection");
        try{
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();
                Log.d("asd","OK");
            }else{
                Log.d("asd","error");
            }
        }
        catch (Exception ex)
        {
            Log.d("Networking", ex.getLocalizedMessage());
            throw new IOException("Error connecting");
        }
        return in;
    }

    private Bitmap DownloadImage(String URL)
    {
        Bitmap bitmap = null;
        InputStream in = null;
        try {
            in = OpenHttpConnection(URL);
            Log.d("in", String.valueOf(in));
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        } catch (IOException e1) {
            Log.d("NetworkingActivity", e1.getLocalizedMessage());
        }
        return bitmap;
    }

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {

        protected Bitmap doInBackground(String... urls) {
            Log.d("aSD","ASD");
            return DownloadImage(urls[0]);
        }

        protected void onPostExecute(Bitmap result) {
            ImageView img = (ImageView) findViewById(R.id.img);
            img.setImageBitmap(result);
        }
    }

    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new DownloadImageTask().execute("http://www.mayoff.com/5-01cablecarDCP01934.jpg");

    }

activity_main.xml activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    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.myapplication.MainActivity">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/img"/>
</RelativeLayout>

Last add this to manifest 最后添加此清单

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

Result 结果 在此处输入图片说明

If it really not working consider check your emulator or device network connection. 如果确实不起作用,请考虑检查模拟器或设备网络连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM