为什么我的自定义列表视图不显示任何内容(安卓工作室)

5cnsuln7  于 2021-06-30  发布在  Java
关注(0)|答案(0)|浏览(234)

我确实在做我的作业,但这已经发生两次了。我仍然不知道为什么它没有出现。我只是简单地把我的讲师代码复制到我的代码中,然后修改一些东西。相信我,php没有什么问题。我真的很感谢你的帮助。谢谢您
自定义列表布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:orientation="vertical"
tools:context=".MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="1">

    <ImageView
        android:id="@+id/imageBox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.6"
        app:srcCompat="@mipmap/camera" />

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:id="@+id/saveButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Save" />

    <Button
        android:id="@+id/cameraButton"
        android:layout_width="156dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text=" Take A Picture" />

    <Button
        android:id="@+id/galeryButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Galery" />

</LinearLayout>

<ListView
    android:id="@+id/pictureLv"
    style="@android:style/Widget.DeviceDefault.ExpandableListView"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:headerDividersEnabled="false"
    android:visibility="visible" />
</LinearLayout>

主要布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:orientation="vertical"
tools:context=".MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="1">

    <ImageView
        android:id="@+id/imageBox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.6"
        app:srcCompat="@mipmap/camera" />

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:id="@+id/saveButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Save" />

    <Button
        android:id="@+id/cameraButton"
        android:layout_width="156dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text=" Take A Picture" />

    <Button
        android:id="@+id/galeryButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Galery" />

</LinearLayout>

<ListView
    android:id="@+id/pictureLv"
    style="@android:style/Widget.DeviceDefault.ExpandableListView"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:headerDividersEnabled="false"
    android:visibility="visible" />
</LinearLayout>

图片对象类

package com.example.trina.lab4;

public class Picture {
String picid;

public Picture(String pid){
    this.picid = pid;

}
}

请求处理程序

package com.example.trina.lab4;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

public class RequestHandler {

public String sendPostRequest(String requestURL,
                              HashMap<String, String> postDataParams) {
    URL url;
    StringBuilder sb = new StringBuilder();
    try {
        url = new URL(requestURL);
        HttpURLConnection conn = (HttpURLConnection)
                url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(10000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(getPostDataString(postDataParams));
        writer.flush();
        writer.close();
        os.close();
        int responseCode = conn.getResponseCode();
        if (responseCode == HttpsURLConnection.HTTP_OK) {
            BufferedReader br = new BufferedReader(new
                    InputStreamReader(conn.getInputStream()));
            sb = new StringBuilder();
            String response;
            //Reading server response
            while ((response = br.readLine()) != null){
                sb.append(response);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return sb.toString();
}

public String sendGetRequest(String requestURL){
    StringBuilder sb =new StringBuilder();
    try {
        URL url = new URL(requestURL);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        BufferedReader bufferedReader = new BufferedReader
                (new InputStreamReader(con.getInputStream()));
        String s;
        while((s=bufferedReader.readLine())!=null){
            sb.append(s+"\n");
        }
    }catch(Exception e){
    }
    return sb.toString();
}

public String sendGetRequestParam(String requestURL, String id){
    StringBuilder sb =new StringBuilder();
    try {
        URL url = new URL(requestURL+id);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        BufferedReader bufferedReader = new BufferedReader
                (new InputStreamReader(con.getInputStream()));
        String s;
        while((s=bufferedReader.readLine())!=null){
            sb.append(s+"\n");
        }
    }catch(Exception e){
    }
    return sb.toString();
}

private String getPostDataString(HashMap<String, String> params)
        throws UnsupportedEncodingException {
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for (Map.Entry<String, String> entry : params.entrySet()) {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
    }
    return result.toString();
}
}

主要活动java

package com.example.trina.lab4;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;   
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {
ImageView image1;
Button saveBtn, cameraBtn, galleryBtn;
static final int REQUEST_IMAGE_CAPTURE = 1;
String serverurl= "http://trinandadinantio.com";
ListView pictureListView;
ArrayList<HashMap<String, String>> pictureList;
Picture picture[];
public final static int PICK_PHOTO_CODE = 1046;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initView();
    pictureList = new ArrayList<>();
    image1 = findViewById(R.id.imageBox);
    saveBtn = findViewById(R.id.saveButton);
    cameraBtn = findViewById(R.id.cameraButton);
    galleryBtn = findViewById(R.id.galeryButton);
    pictureListView = findViewById(R.id.pictureLv);
    loadPicture();

    saveBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String pictureName = "a";
            insertPicture(pictureName);
        }
    });

    cameraBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent takePictureIntent = new  
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != 
null) {
                startActivityForResult(takePictureIntent, 
REQUEST_IMAGE_CAPTURE);
            }
        }
    });

    galleryBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_PICK,

 android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent, PICK_PHOTO_CODE);
        }});

    }

private void insertPicture(final String pictureName) {
    class InsertPicture extends AsyncTask<Void,Void,String> {

        @Override
        protected String doInBackground(Void... params) {
            HashMap<String,String> hashMap = new HashMap<>();
            hashMap.put("pictureName",pictureName);
            RequestHandler rh = new RequestHandler();
            String s = rh.sendPostRequest(serverurl +"/Lab4
/insert.php",hashMap);
            return s;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            String[] sarray = s.split("\\s*,\\s*");
            String success = sarray[0];
            String imagename = sarray[1];
            if (success.equals("success")){
                new Encode_image().execute(getDir(),imagename+".jpg");

            }else{
                Toast.makeText(MainActivity.this, "Failed",
                        Toast.LENGTH_LONG).show();
            }
        }
    }
    try {
        InsertPicture iPic = new InsertPicture();
        iPic.execute();
    }catch(Exception e){}
}

private void initView() {
    pictureListView = findViewById(R.id.pictureLv);
    image1 = findViewById(R.id.imageBox);
    saveBtn = findViewById(R.id.saveButton);
    cameraBtn = findViewById(R.id.cameraButton);
    galleryBtn = findViewById(R.id.galeryButton);
}

protected void onActivityResult(int requestCode, int resultCode, Intent
data) {

    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {

        int displayWidth = 
getWindowManager().getDefaultDisplay().getWidth();
        int displayHeight =
getWindowManager().getDefaultDisplay().getHeight();
        image1.getLayoutParams().height = displayHeight / 4;
        image1.getLayoutParams().width = displayWidth;
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");
        imageBitmap = ThumbnailUtils.extractThumbnail(imageBitmap, 
800,600);
        //imageBitmap = rotateBmp(imageBitmap);
        image1.setImageBitmap(imageBitmap);
        image1.buildDrawingCache();
        ContextWrapper cw = new ContextWrapper(this);
        File pictureFileDir = cw.getDir("picture", Context.MODE_PRIVATE);
        if (!pictureFileDir.exists()) {
            pictureFileDir.mkdir();
        }
        Log.e("FILE NAME", "" + pictureFileDir.toString());
        if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
            return;
        }
        FileOutputStream outStream = null;
        String photoFile = "image.jpg";
        File outFile = new File(pictureFileDir, photoFile);
        try {
            outStream = new FileOutputStream(outFile);
            imageBitmap.compress(Bitmap.CompressFormat.JPEG, 90, 
outStream);
            outStream.flush();
            outStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //ExifInterface ei = new ExifInterface(outFile.getAbsolutePath());
        //int orientation = 
ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
        //       ExifInterface.ORIENTATION_UNDEFINED);
        //Toast.makeText(cw, "ORIENTATION"+orientation,
Toast.LENGTH_SHORT).show();
    }else {
        try {
            Uri photoUri = data.getData();
            int displayWidth = 
getWindowManager().getDefaultDisplay().getWidth();
            int displayHeight = 
getWindowManager().getDefaultDisplay().getHeight();
            image1.getLayoutParams().height = displayHeight / 4;
            image1.getLayoutParams().width = displayWidth;
            Bitmap imageBitmap;
            imageBitmap = 
MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
            imageBitmap = ThumbnailUtils.extractThumbnail(imageBitmap, 
800,600);
            //imageBitmap = rotateBmp(imageBitmap);
            image1.setImageBitmap(imageBitmap);
            image1.buildDrawingCache();
            ContextWrapper cw = new ContextWrapper(this);
            File pictureFileDir = cw.getDir("picture",
Context.MODE_PRIVATE);
            if (!pictureFileDir.exists()) {
                pictureFileDir.mkdir();
            }
            Log.e("FILE NAME", "" + pictureFileDir.toString());
            if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
                return;
            }
            FileOutputStream outStream = null;
            String photoFile = "image.jpg";
            File outFile = new File(pictureFileDir, photoFile);
            try {
                outStream = new FileOutputStream(outFile);
                imageBitmap.compress(Bitmap.CompressFormat.JPEG, 90, 
outStream);
                outStream.flush();
                outStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }catch (IOException e) {
            e.printStackTrace();
        }

    }
}

public Bitmap rotateBmp(Bitmap bmp){
    Matrix matrix = new Matrix();
    //set image rotation value to 90 degrees in matrix.
    matrix.postRotate(90);
    //supply the original width and height, if you don't want to change 
the height and width of bitmap.
    bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(),bmp.getHeight(), 
matrix, true);
    return bmp;
}

private void makeRequest(final String encoded_string, final String 
image_name) {
    class UploadAll extends AsyncTask<Void, Void, String> {

        private ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setTitle("Uploading Image");
            progressDialog.setMessage("in progress...");
            progressDialog.setIndeterminate(false);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setCancelable(false);
            progressDialog.show();
        }
        @Override
        protected String doInBackground(Void... params) {
            HashMap<String, String> map = new HashMap<>();
            map.put("encoded_string", encoded_string);
            map.put("image_name", image_name);
            RequestHandler rh = new RequestHandler();//request server 
connection
            String s = rh.sendPostRequest(serverurl+"/Lab4
/upload_image.php", map);
            return s;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            progressDialog.dismiss();
            loadPicture();
        }
    }
    try

    {
        UploadAll uploadall = new UploadAll();
        uploadall.execute();
    } catch (
            Exception e)

    {
    }
}

private void loadPicture() {

    class LoadPicture extends AsyncTask<Void,Void,String> {

        @Override
        protected String doInBackground(Void... params) {
            HashMap<String,String> hashMap = new HashMap<>();
            RequestHandler rh = new RequestHandler();
            String s = rh.sendPostRequest(serverurl 
+"/Lab4archall.php",hashMap);
            return s;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            pictureList.clear();
            if (s != null) {
                try {
                    JSONObject jsonObj = new JSONObject(s);
                    System.out.print(s);
                    JSONArray pictureArray =
jsonObj.getJSONArray("picture");
                    picture = new Picture[pictureArray.length()];
                    for (int i = 0; i < pictureArray.length(); i++) {
                        JSONObject c = pictureArray.getJSONObject(i);
                        String pid = c.getString("picid");

                        picture[i] = new Picture(pid);
                        HashMap<String, String> picturels = new 
HashMap<>();
                        picturels.put("pictureid",pid);
                        pictureList.add(picturels);
                    }
                }catch (final JSONException e) {}

                ListAdapter adapter = new CustomList(
                        MainActivity.this, pictureList,
                        R.layout.activity_custom_list, new String[]
                        {"pictureid"}, new int[]
                        {R.id.pictureId});
                pictureListView.setAdapter(adapter);

            }
        }
    }
    try {
        LoadPicture lPicture = new LoadPicture();
        lPicture.execute();
    }catch(Exception e){}
}

public class Encode_image extends AsyncTask<String,String,Void> {
    private String encoded_string, image_name;
    Bitmap bitmap;

    @Override
    protected Void doInBackground(String... args) {
        String filename = args[0];
        image_name = args[1];
        bitmap = BitmapFactory.decodeFile(filename);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
        byte[] array = stream.toByteArray();
        encoded_string = Base64.encodeToString(array, 0);
        return null;
    }

    @Override
    protected void onPostExecute(Void avoid) {
        //Log.e("Hanis",""+encoded_string);
        makeRequest(encoded_string, image_name);
    }
}

public String getDir(){
    ContextWrapper cw = new ContextWrapper(this);
    File pictureFileDir = cw.getDir("picture", Context.MODE_PRIVATE);
    if (!pictureFileDir.exists()) {
        pictureFileDir.mkdir();
    }
    Log.d("GETDIR",pictureFileDir.getAbsolutePath());
    return pictureFileDir.getAbsolutePath()+"/image.jpg";
}
}

自定义列表。java(适配器类)

package com.example.trina.lab4;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CustomList extends SimpleAdapter {

private Context mContext;
public LayoutInflater inflater=null;
public CustomList(Context context, List<? extends Map<String, ?>> data, 
int 
resource, String[] from, int[] to) {
    super(context, data, resource, from, to);
    mContext = context;
    inflater =
(LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View vi=convertView;
    if(convertView==null)
        vi = inflater.inflate(R.layout.activity_custom_list, parent, 
false);
    HashMap<String, Object> data = (HashMap<String, Object>) 
getItem(position);
    TextView picID = (TextView)vi.findViewById(R.id.pictureId);
    String picid = (String) data.get("picid");
    picID.setText(picid);
    ImageView image = vi.findViewById(R.id.imageBox2);
    String image_url = "http://trinandadinantio.com/Lab4/picture
/"+picid+".jpg";

Picasso .get().load(image_url).resize(200,150).networkPolicy(NetworkPoli
cy.NO_CACHE).memoryPolicy(MemoryPolicy.NO_CACHE).into(image);
    return vi; 
}
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题