【问题标题】:i want to send Listview Data to Another Activity in Android using json我想使用 json 将 Listview 数据发送到 Android 中的另一个 Activity
【发布时间】:2015-12-01 10:09:17
【问题描述】:

我想将Listview 数据发送给另一个Activity

检查我的代码:

ActorAdapter.java

package anyname;

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

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;

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);
        }

    }

Actors.java

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;
    }

}

MainActivity.java

package ANYNAME;

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

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 android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

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("json link here.xml");

        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();              
            }
        });
    }


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

        ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(MainActivity.this);
            dialog.setMessage("Loading, please wait");
            dialog.setTitle("Connecting server");
            dialog.show();
            dialog.setCancelable(false);
        }

        @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) {
            dialog.cancel();
            adapter.notifyDataSetChanged();
            if(result == false)
                Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();

        }
    }






}

当用户点击 Listview 内容并将 Listview 数据传递给 NewActivity.java

【问题讨论】:

  • 你想发送整个actorsList还是只发送一个选中的?
  • 一个选定的列表视图内容...到另一个活动
  • 使用Intent向其他Activity发送数据
  • 因此,您在 Actors 类中实现 Parceable,将其作为 Extra 放入 Intent 并在目标活动中检索 Extra。这个过程的哪一部分是问题?这里的实际问题是什么?

标签: java android json listview android-listview


【解决方案1】:

您可以使用Intent 将数据从一个Activity 传递到另一个。

Intent intent=new Intent(MainActivity.this,NewActivity.class); 
intent.putExtra("key",value);//
......
startActivity(intent);

在您的NewActivity 访问值中:

 variable=getIntent().getXXX("key");

【讨论】:

    【解决方案2】:

    尝试使用GSON 库从您的模型生成 json(字符串)。把它放到Intent 并开始新的Activity

    【讨论】:

      【解决方案3】:

      您可以使用共享的 SharedPrefences

      SharedPreferences pref = getSharedPreferences("MYPrefrences", 0);
      

      保存

      Editor prefsEditor = pref.edit();
      
      Gson gson = new Gson();
      
      String json = gson.toJson("MyObject");
      
      prefsEditor.putString("MyObject", json);
      
      prefsEditor.commit();
      

      为了得到

      Gson gson = new Gson();
      
      String json = mPrefs.getString("MyObject", "");
      
      Actor actor = gson.fromJson(json, Actor.class);
      

      【讨论】:

        【解决方案4】:

        在您的 Actors.java 类中实现 Serializable (http://developer.android.com/reference/java/io/Serializable.html)。在您的 setOnItemClickListener 中,使用以下代码:

        Intent newIntent = new Intent(thisActivity.this, NextActivity.class);
        newIntent.putExtra("key", value);
        startActivity(newIntent);
        

        在您的 NextActivity.class 中,您可以像这样取回对象:

        Intent intent = getIntent();
        YourClass object = intent.getSerializableExtra("key");
        

        这将为您提供整个对象及其所有属性。

        【讨论】:

          【解决方案5】:

          用这个替换你的代码,

              @Override
          public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                  long id) {
          
              Actors myActor = actorsList.get(position);
          
              // create JSON object from the above object with getter methods
              JSONObject myActorJSON = new JSONObject();
              myActorJSON.put("name", myActor.getName());
              myActorJSON.put("description", myActor.getDescription());
              myActorJSON.put("dob", myActor.getDOB());
              myActorJSON.put("country", myActor.getCountry());
              myActorJSON.put("height", myActor.getHeight());
              myActorJSON.put("spouse", myActor.getSpouse());
              myActorJSON.put("children", myActor.getChildren());
              myActorJSON.put("image", myActor.getImage());
          
              //you can send the Actors object or JSONObject to the new Activity
              // through intent as
              Intent i = new Intent(this, NewActivity.class);
              i.putExtra("ACTOR_OBJECT", myActor);    //Actors class should extend serializable interface
              i.putExtra("ACTOR_JSON_OBJECT", myActorJSON.toString());
              startActivity(i);
          }
          

              //Now in NewActivity.class extract tha data from intent as
          Intent i = getIntent();
          Actors receivedActorObject = (Actors)i.getSerializableExtra("ACTOR_OBJECT");
          String JSONString = i.getStringExtra("ACTOR_JSON_OBJECT");
          try {
              JSONObject receivedActorJSON = new JSONObject(JSONString);
          } catch (JSONException e) {
              e.printStackTrace();
          }
          

          让我知道它是否适合您... 并将其标记为答案,以便对其他人有用...

          【讨论】:

            【解决方案6】:

            关于你的 onClick 方法

            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();
                        Actor selectedActor = actorsList.get(position);
                        JSONObject obj = new JsonObject();
                        obj.put("name",selectedActor.getName());
                        //add other values of actor like that
                        Intent i = new Intent(MainActirity.this,otherActivity.class);
                        i.putExtra("Actor",obj.toString());
                        startActivity(i);
            
                    }
            

            在您的接收活动中

            Intent i = getIntent();
            JSONObject obj = new JSONObject(i.getStringExtra("Actor"));
            

            也可以看看Intent

            【讨论】:

              猜你喜欢
              • 2015-04-08
              • 2015-04-09
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多