java - SplashScreen 中的 AsyncTask

标签 java android json android-asynctask

我制作了一个应用程序,它使用 json 从服务器下载数据并按照 this tutorial. 将其显示在 ListView 中。 但是现在我想在加载时在 SplashScreen 中执行此过程,然后将所有下载的数据发送到 MainActivity。怎样才能做到这一点。 谢谢。

我的主要 Activity

package tutorial.json.com.jsonparsingtutorial;

import android.app.Activity;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import org.apache.http.HttpEntity;
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.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

public class MainActivity extends Activity {

ArrayList<Actors> actorsList;

ActorAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    actorsList = new ArrayList<Actors>();
    new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");

    ListView listview = (ListView)findViewById(R.id.list);
    adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);

    listview.setAdapter(adapter);

    listview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                long id) {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), actorsList.get(position).getName(), Toast.LENGTH_LONG).show();
        }
    });
}


public class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {


    @Override
    protected Boolean doInBackground(String... urls) {
        try {

            //------------------>>
            HttpGet httppost = new HttpGet(urls[0]);
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(httppost);

            // StatusLine stat = response.getStatusLine();
            int status = response.getStatusLine().getStatusCode();

            if (status == 200) {
                HttpEntity entity = response.getEntity();
                String data = EntityUtils.toString(entity);


                JSONObject jsono = new JSONObject(data);
                JSONArray jarray = jsono.getJSONArray("actors");

                for (int i = 0; i < jarray.length(); i++) {
                    JSONObject object = jarray.getJSONObject(i);

                    Actors actor = new Actors();

                    actor.setName(object.getString("name"));
                    actor.setDescription(object.getString("description"));
                    actor.setDob(object.getString("dob"));
                    actor.setCountry(object.getString("country"));
                    actor.setHeight(object.getString("height"));
                    actor.setSpouse(object.getString("spouse"));
                    actor.setChildren(object.getString("children"));
                    actor.setImage(object.getString("image"));

                    actorsList.add(actor);
                }
                return true;
            }

            //------------------>>

        } catch (ParseException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }


    protected void onPostExecute(Boolean result) {
        adapter.notifyDataSetChanged();
        if(result == false)
            Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();

    }
}
}

Actor 适配器

package tutorial.json.com.jsonparsingtutorial;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.InputStream;
import java.util.ArrayList;

public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;

public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
    super(context, resource, objects);
    vi = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    Resource = resource;
    actorList = objects;
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // convert view = design
    View v = convertView;
    if (v == null) {
        holder = new ViewHolder();
        v = vi.inflate(Resource, null);
        holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
        holder.tvName = (TextView) v.findViewById(R.id.tvName);
        holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
        holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
        holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
        holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
        holder.tvSpouse = (TextView) v.findViewById(R.id.tvSpouse);
        holder.tvChildren = (TextView) v.findViewById(R.id.tvChildren);
        v.setTag(holder);
    } else {
        holder = (ViewHolder) v.getTag();
    }
    holder.imageview.setImageResource(R.drawable.ic_launcher);
    new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
    holder.tvName.setText(actorList.get(position).getName());
    holder.tvDescription.setText(actorList.get(position).getDescription());
    holder.tvDOB.setText("B'day: " + actorList.get(position).getDob());
    holder.tvCountry.setText(actorList.get(position).getCountry());
    holder.tvHeight.setText("Height: " + actorList.get(position).getHeight());
    holder.tvSpouse.setText("Spouse: " + actorList.get(position).getSpouse());
    holder.tvChildren.setText("Children: " + actorList.get(position).getChildren());
    return v;

}

static class ViewHolder {
    public ImageView imageview;
    public TextView tvName;
    public TextView tvDescription;
    public TextView tvDOB;
    public TextView tvCountry;
    public TextView tvHeight;
    public TextView tvSpouse;
    public TextView tvChildren;

}

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

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }

}
}

Actor类

package tutorial.json.com.jsonparsingtutorial;

public class Actors {

private String name;
private String description;
private String dob;
private String country;
private String height;
private String spouse;
private String children;
private String image;

public Actors() {
    // TODO Auto-generated constructor stub
}

public Actors(String name, String description, String dob, String country,
              String height, String spouse, String children, String image) {
    super();
    this.name = name;
    this.description = description;
    this.dob = dob;
    this.country = country;
    this.height = height;
    this.spouse = spouse;
    this.children = children;
    this.image = image;
}


public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getDob() {
    return dob;
}

public void setDob(String dob) {
    this.dob = dob;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

public String getHeight() {
    return height;
}

public void setHeight(String height) {
    this.height = height;
}

public String getSpouse() {
    return spouse;
}

public void setSpouse(String spouse) {
    this.spouse = spouse;
}

public String getChildren() {
    return children;
}

public void setChildren(String children) {
    this.children = children;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

}

最佳答案

您需要创建 SplashScrenActivity 并使用 JSONAsyncTask 下载数据,一旦收到响应,您必须在 onPost 中启动 MainActivity 并将下载的数据发送到 MainActivity。当 JSONAsyncTask 正在执行时,您可以在 onPreExecute 中显示 ProgressBar 并在 onPostExecute 中隐藏 ProgressBar。

要将数据发送到 MainActivity,您需要让您的 Actor 类实现 Parcelable 接口(interface)。一旦 Actor 类实现了 Parcelable,这就是您发送数据的方式,从 SplashScreenActivity 到 MainActivty -

在 SplashScreenActivity 中,

Intent intent = new Intent(SplashScreenActivity.this,MainActivty.class);
intent.putParcelableArrayListExtra("ActorsList", actorsArrayList);
startActivity(intent);

在 MainActivty onCreate() 中,您可以使用 ActorsList,

if (getIntent().hasExtra("ActorsList")) {

            ArrayList<Actors> actorsList =
                    getIntent().getParcelableArrayListExtra("ActorsList");
}

这将是您的 Parcelable 实现类,

public class Actors implements Parcelable {

    private String name;
    private String description;
    private String dob;
    private String country;
    private String height;
    private String spouse;
    private String children;
    private String image;

    public Actors() {
        // TODO Auto-generated constructor stub
    }

    public Actors(String name, String description, String dob, String country,
                  String height, String spouse, String children, String image) {
        super();
        this.name = name;
        this.description = description;
        this.dob = dob;
        this.country = country;
        this.height = height;
        this.spouse = spouse;
        this.children = children;
        this.image = image;
    }


    protected Actors(Parcel in) {
        name = in.readString();
        description = in.readString();
        dob = in.readString();
        country = in.readString();
        height = in.readString();
        spouse = in.readString();
        children = in.readString();
        image = in.readString();
    }

    public static final Creator<Actors> CREATOR = new Creator<Actors>() {
        @Override
        public Actors createFromParcel(Parcel in) {
            return new Actors(in);
        }

        @Override
        public Actors[] newArray(int size) {
            return new Actors[size];
        }
    };

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getDob() {
        return dob;
    }

    public void setDob(String dob) {
        this.dob = dob;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getHeight() {
        return height;
    }

    public void setHeight(String height) {
        this.height = height;
    }

    public String getSpouse() {
        return spouse;
    }

    public void setSpouse(String spouse) {
        this.spouse = spouse;
    }

    public String getChildren() {
        return children;
    }

    public void setChildren(String children) {
        this.children = children;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(name);
        parcel.writeString(description);
        parcel.writeString(dob);
        parcel.writeString(country);
        parcel.writeString(height);
        parcel.writeString(spouse);
        parcel.writeString(children);
        parcel.writeString(image);
    }
}

在 onPostExecute 中,你只需要像下面这样启动 MainActivity,

Intent intent = new Intent(context, MainActivity.class);
intent.putParcelableArrayListExtra("ActorsList", actorsArrayList);
startActivity(intent);

有关如何使类可打包的更多信息,请引用以下链接 - How can I make my custom objects Parcelable?

关于java - SplashScreen 中的 AsyncTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41907921/

相关文章:

java - 如何访问 Google Apps for Business 用户的日历空闲/忙碌信息?

java - 无法使用 Spring Security 配置无状态和有状态 http 部分..?

android - 如何正确暂停AudioTrack并恢复平稳播放?

java - 您可以通过市场要求对 Android 应用程序进行年度升级吗

android - 如何在android中的MAPBOX中获取当前位置

javascript - 使用 Node.js 连接和聚合 json 对象数据

Java 堆内存使用量增加

java - 如何从字符串图像中获取像素 RGB 值? .get 不适用于 imageLoader(处理中)

json - 替换 JSON 值

java - 在 Java 中测试两个 JSON 对象的相等性并忽略子顺序