[英]How to send dynamic data from one activity to another in android
我正在開發一個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();
?>
更換
i1.putExtra("CompName", CompName);
通過
i1.putExtra("CompName", r[position]);
然后在下一個活動中獲取此數據,並根據傳遞的值從數據庫中獲取數據。
您必須傳遞用戶選擇的值。 因此,所有值都在適配器r
,您將了解按項目選定位置( onItemClick
第三個參數)選擇了哪個用戶。 所以應該是r[position]
。 最好在將適配器設置為ListView之前完全填充適配器。 因此,從JSON中獲取所有數據,將其添加到適配器,然后將該適配器設置為ListView。
嘗試使用AsyncTasks,這里是文檔: http : //developer.android.com/reference/android/os/AsyncTask.html
試試這個,你必須在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");
嘗試這種方式,希望這將幫助您解決問題。
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.