我是Android开发的初学者。 它可能看起来非常基本,但我真的很难让它在我的项目中运行。
我正在为教授开发一个应用程序,以查看所有在数据库中试用的学生名单。
在我们将帐户登录到应用程序后的进度中,数据库中的所有学生都将以ListView
形式显示
这是我的活动代码
UPDATE1:我管理以使项目可点击并显示名为Profile.class的新活动 (我希望它能显示出来 学生姓名:显示姓名 学生ID:显示身份 但它显示为NULL)
这是我的更新代码
public class MainPage extends Activity {
TextView name,email;
private String jsonResult;
private String url = "http://192.168.254.106/notificationapp/students.php";
private ListView listView;
String stud_name, stud_id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainpage_layout);
name = (TextView)findViewById(R.id.name);
email = (TextView)findViewById(R.id.email);
Bundle bundle = getIntent().getExtras();
name.setText("Welcome "+bundle.getString("name"));
email.setText("Email: "+bundle.getString("email"));
listView = (ListView) findViewById(R.id.listView);
accessWebService();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
@Override
protected void onPostExecute(String result) {
ListDrawer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
task.execute(new String[] { url });
}
public void ListDrawer() {
final List<Map<String, String>> studentList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("student_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("student_name");
String number = jsonChildNode.optString("student_id");
String outPut = name + "-" + number;
studentList.add(createStudent("Students", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
////////////////////////////////// UPDATE LISTVIEW ITEMS ONCLICK
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
studentList.get(position);
//Do your logic for getting the student variables here
Intent intent = new Intent(MainPage.this,Profile.class);
Bundle b = new Bundle();
b.putString("student_name", stud_name);
b.putString("student_id", stud_id);
intent.putExtras(b);
startActivity(intent);
}
});
//////////////////////////////////////UPDATE END
SimpleAdapter simpleAdapter = new SimpleAdapter(this, studentList,
android.R.layout.simple_list_item_1,
new String[] { "Students" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
Toast.makeText(getApplication(), "Logged in Successfully", Toast.LENGTH_SHORT).show();
}
private HashMap<String, String> createStudent(String name, String number) {
HashMap<String, String> Students = new HashMap<String, String>();
Students.put(name, number);
return Students;
}
}
我的个人资料活动
public class Profile extends Activity {
TextView stud_name,stud_id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_layout);
stud_name = (TextView)findViewById(R.id.student_name);
stud_id = (TextView)findViewById(R.id.student_id);
Bundle bundle = getIntent().getExtras();
stud_name.setText("Student name: "+bundle.getString("student_name"));
stud_id.setText("Student ID: "+bundle.getString("student_id"));
}
}
我认为我的问题是在我的php中如何配置它 如果我使用捆绑方法?从ListView中单击一个项目后,从mysql获取字符串数据并将其发送到Profile活动?
<?php
$host="localhost";
$username="thesis";
$password="thesis123";
$db_name="professor_db";
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from student_info";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['student_info'][]=$row;
}
}
mysql_close($con);
echo json_encode($json);
?>
答案 0 :(得分:1)
您可以为listview的每个元素创建一个customListView附加clickListener,clickListener将通过INTENT将您带到另一个活动,您也可以使用INTENT发送一些数据,以便您的新活动将被填充。
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class CustomAdapter extends BaseAdapter{
String [] result;
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomAdapter(MainActivity mainActivity, String[] prgmNameList, int[] prgmImages) {
// TODO Auto-generated constructor stub
result=prgmNameList;
context=mainActivity;
imageId=prgmImages;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tv;
ImageView img;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.program_list, null);
holder.tv=(TextView) rowView.findViewById(R.id.textView1);
holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
holder.tv.setText(result[position]);
holder.img.setImageResource(imageId[position]);
rowView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_LONG).show();
}
});
return rowView;
}
}
答案 1 :(得分:1)
您可以在ListView上设置onItemClickListener。在onClick方法中,您可以根据所选位置从阵列中获取学生。使用该数据,您可以创建一个Intent with extras并启动它。例如:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
... studentList.get(position); //Do your logic for getting the student variables here
Intent intent = new Intent(MainPage.this, TargetActivity.class);
intent.putExtra("name", studentName);
intent.putExtra("id", studentId);
startActivity(intent);
}
});
在TargetActivity(或项目中调用的内容)中,在onCreate方法中添加:
Intent intent = getIntent();
String studentName = intent.getStringExtra("name");
int studentId = intent.getIntExtra("id",-1);
答案 2 :(得分:0)
您可以为所有可用的学生的基本和常见信息创建一个班级,创建其get()
&amp; set()
方法。
您从json获取的数据使用它的set()
方法存储它
喜欢:
public class StudentInfo{
public String stud_name, stud_id ,stud_roll_num ,stud_add;
// get Student Name with this method
public String getName() {
return stud_name;
}
// set Student Name with this method
public void setName(String name) {
this.stud_name = name;
}
public String getRollNum() {
return stud_roll_num;
}
public void setRollNum(String rollNum) {
this.stud_roll_num = rollNum;
}
}
然后像这样使用它:
public ArraryList<StudentInfo> studinfo = new ArraryList<StudentInfo>();
String name = studinfo.get(position).stud_name;
String roll_num = studinfo.get(position).stud_roll_num;