【问题标题】:How to send dynamic data from one activity to another in android如何在android中将动态数据从一个活动发送到另一个活动
【发布时间】:2014-07-26 04:53:25
【问题描述】:

我正在开发一个 android 应用程序,我从 mysql 数据库中获取数据并在 Listview 中显示该数据。我有电信、银行、社交网站等数据“类别”。这个从 mysql 获取的 Category 完美地显示在 ListView 中。现在,当我单击其中任何一个时,它应该移动到下一个活动并根据该类别显示数据。假设我点击社交网站,然后在下一个活动中,数据应该是 Google Plus、Instagram、Twitter 等,这个列表将来自数据库并显示在列表视图中。我不知道该怎么做..!!!请帮助我...这是我所做的代码。

Welcome.java

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class Welcome extends Activity 
{
    TextView text;
    //Button b1,b2,b3;
    String CompName,CompID;

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

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

      //  b1=(Button)findViewById(R.id.dashboard_tab1);
      //  b1.setOnClickListener(this);

        connect();
    }

    public void connect() 
    {
        String data;
        List<String> r = new ArrayList<String>();
        ArrayAdapter<String>adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,r);
        ListView list=(ListView)findViewById(R.id.list);
        try 
        {
                DefaultHttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet("http://10.0.2.2/database/Retrive.php");
                HttpResponse response = client.execute(request);
                HttpEntity entity=response.getEntity();
                data=EntityUtils.toString(entity);
                Log.e("STRING", data);

                try 
                {
                   JSONArray json=new JSONArray(data);
                   for(int i=0;i<json.length(); i++)
                   {
                        JSONObject obj=json.getJSONObject(i);

                        CompName=obj.getString("fldCompName");
                        CompID=obj.getString("fldCompID");

                        Log.e("STRING", CompName);
                        Log.e("STRING",CompID);

                        r.add(CompName);
                        //r.add(CompID);
                        list.setAdapter(adapter);

                        list.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() 
                        {
                            @Override
                            public void onItemClick(AdapterView<?> parent,View view, int position, long id) 
                            {
                                Intent i1=new Intent(Welcome.this,Category1.class);
                                i1.putExtra("CompName", CompName);
                                startActivity(i1);
                            }
                        });
                   }
                } 
                catch (JSONException e) 
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } catch (ClientProtocolException e) {
                Log.d("HTTPCLIENT", e.getLocalizedMessage());
            } catch (IOException e) {
                Log.d("HTTPCLIENT", e.getLocalizedMessage());
            }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.welcome, menu);
        return true;
    }
}

这是我的布局文件...!!!

activity_welcome.xml

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

<ListView
    android:id="@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/bg" >
</ListView>

</LinearLayout>

Retrive.php

<?php

    $host='localhost';
    $uname='root';
    $pwd='';
    $db='database';

    $con=mysqli_connect($host,$uname,$pwd) or die("Connection Failed");
        mysqli_select_db($con,$db) or die("database selection failed");

    $sql=mysqli_query($con,"select fldCompName,fldCompID from tblCompanies where fldStatus='1'");
    while($row=mysqli_fetch_assoc($sql))
    $output[]=$row;
    $a=json_encode($output);
    print($a);
    mysqli_close();

?>

【问题讨论】:

  • 您是否获得了所有数据?我的意思是,您的所有数据都在 1 个表中,或者在不同表中的类别明智?

标签: php android mysql json listview


【解决方案1】:

替换

 i1.putExtra("CompName", CompName);

通过

 i1.putExtra("CompName", r[position]);

然后在下一个活动中获取此数据,并根据传递的值从 DB 中获取数据。

您必须传递用户选择的值。因此,您的所有值都在您的适配器r 中,您将通过项目选择位置了解哪个用户已选择,这是onItemClick 的第三个参数。所以应该是r[position]。最好在将适配器设置为 ListView 之前将其完全填充。因此,从 JSON 中获取所有数据,将其添加到适配器,然后将该适配器设置为 ListView。

【讨论】:

    【解决方案2】:

    尝试使用 AsyncTasks,这里是文档:http://developer.android.com/reference/android/os/AsyncTask.html

    【讨论】:

      【解决方案3】:

      试试这个,你必须使用 put extra's 到 Intent 并将数据发送到其他活动并在下一个活动的 onCreate 上获取它

       listView.setOnItemClickListener(new OnItemClickListener() {
      
              @Override
              public void onItemClick(AdapterView<?> arg0, View view, int pos,
                      long id) {
                  SubCategoryModel scm = lstSubCategoryList.get(pos);
                  Intent intent = new Intent(prestentactivity.this, nextactivity.class);
                  intent.putExtra("ActivityKey", scm.getName());
      
                  startActivity(intent);
      
              }
      
      
          });
      

      下一个活动

      Intent intent = getIntent();
       String Key= intent.getStringExtra("ActivityKey");
      

      【讨论】:

        【解决方案4】:

        试试这个方法,希望能帮助你解决问题。

        public class Welcome extends Activity
        {
        
            private ListView list;
            private ArrayAdapter<String> adapter;
            private ArrayList<HashMap<String,String>> data;
        
            @Override
            protected void onCreate(Bundle savedInstanceState)
            {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_welcome);
                list=(ListView)findViewById(R.id.list);
        
                list.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener()
                {
                    @Override
                    public void onItemClick(AdapterView<?> parent,View view, int position, long id)
                    {
                        Intent i1=new Intent(Welcome.this,Category1.class);
                        i1.putExtra("CompName",data.get(position).get("CompName"));
                        i1.putExtra("fldCompID",data.get(position).get("fldCompID"));
                        startActivity(i1);
                    }
                });
                getDataFromServer(new CallListener() {
                    @Override
                    public void onComplete(ArrayList<HashMap<String, String>> response) {
                        data = response;
                        String[] listItemArray = new String[data.size()];
                        for (int i = 0; i < data.size(); i++) {
                            listItemArray[i] = data.get(i).get("CompName");
                        }
                        adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, listItemArray);
                        list.setAdapter(adapter);
                    }
                });
        
            }
        
            @Override
            public boolean onCreateOptionsMenu(Menu menu)
            {
                getMenuInflater().inflate(R.menu.welcome, menu);
                return true;
            }
        
            public void getDataFromServer(final CallListener target){
                new AsyncTask<Void, Void, ArrayList<HashMap<String, String>>>() {
                    ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
                    @Override
                    protected ArrayList<HashMap<String, String>> doInBackground(Void... params) {
                        try {
                            DefaultHttpClient client = new DefaultHttpClient();
                            HttpGet request = new HttpGet("http://10.0.2.2/database/Retrive.php");
                            HttpResponse response = client.execute(request);
                            HttpEntity entity=response.getEntity();
                            Log.e("STRING", EntityUtils.toString(entity));
        
        
                            JSONArray json = new JSONArray(EntityUtils.toString(entity));
        
                            for (int i = 0; i < json.length(); i++) {
                                Log.e("STRING", json.getJSONObject(i).getString("fldCompName"));
                                Log.e("STRING", json.getJSONObject(i).getString("fldCompID"));
        
                                HashMap<String, String> row = new HashMap<String, String>();
                                row.put("CompName", json.getJSONObject(i).getString("fldCompName"));
                                row.put("fldCompID", json.getJSONObject(i).getString("fldCompID"));
                                data.add(row);
                            }
                        }catch (Throwable e){
                            e.printStackTrace();
                        }
                        return data;
                    }
        
                    @Override
                    protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
                        super.onPostExecute(result);
                        target.onComplete(result);
        
                    }
                }.execute();
            }
        
            interface CallListener{
                public void onComplete(ArrayList<HashMap<String,String>> response);
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-05-03
          • 2020-02-11
          • 2019-07-31
          • 2017-01-07
          • 2014-09-06
          • 1970-01-01
          • 2016-11-04
          • 2012-07-20
          相关资源
          最近更新 更多