【发布时间】:2014-02-09 05:59:08
【问题描述】:
我正在开发一个 android 应用程序,该应用程序将导航抽屉实现为主菜单,然后取决于我执行操作的选择。现在的任务之一是使用 jdbc 从在线 mysql 数据库主机填充列表视图。我能够在正常活动中填充列表视图,但相同的代码在片段中不起作用。这就是我的 Fragment 的样子:
public class HomeFragment extends Fragment
{
private ProgressDialog pDialog;
ListView listView ;
Connection conn=null;
ResultSet rs=null;
PreparedStatement st=null;
List<Map<String,String>> list = new ArrayList<Map<String,String>>();
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.main_list, container, false);
try
{
initList();
} catch (SQLException e)
{
e.printStackTrace();
}
String[] from = { "sender", "subject" ,"file_name"};
int[] to = {R.id.sender,R.id.subject,R.id.file_name};
SimpleAdapter adapter = new SimpleAdapter(getActivity(),list,R.layout.list_item,from,to);
//ListView lv=(ListView) rootView.findViewById(R.id.list);
//getListView();
ListView lv= (ListView) getActivity().findViewById(R.id.list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String sender = ((TextView) view.findViewById(R.id.sender)).getText() .toString();
String subject = ((TextView) view.findViewById(R.id.subject)).getText() .toString();
String fname = ((TextView) view.findViewById(R.id.file_name)).getText() .toString();
}
});
return rootView;
}
public void initList() throws SQLException
{
String username="sql428447";
String pass="************";
String sender,subject,file_name;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://sql4.freesqldatabase.com:3306/sql428447",username,pass);
}
catch(Exception x)
{
x.printStackTrace();
}
try
{
String sql="select sender,subject,file_name from files";
st=conn.prepareStatement(sql);
rs=st.executeQuery();
while(rs.next())
{
sender=rs.getString(1);
subject=rs.getString(2);
file_name=rs.getString(3);
list.add(createRecord(sender, subject,file_name));
}
}
catch(Exception z)
{
z.printStackTrace();
}
finally
{
st.close();
rs.close();
}
}
public HashMap<String, String> createRecord(String key, String name,String file_name)
{
HashMap<String, String> record = new HashMap<String, String>();
record.put( "sender", key);
record.put( "subject", name);
record.put("file_name",file_name);
return record;
}
}
我从导航抽屉选择项中调用这个片段,如下所示:
case 1:
newFragment = new HomeFragment();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
但在运行时记录它在 initlist() 和 st.close() 上抛出的异常,我无法弄清楚。我想我的方法几乎是正确的,这在大多数教程中都有讨论,但我不理解我的代码中的错误,因为它在正常活动中工作。任何帮助,将不胜感激。谢谢 这是异常的截图
【问题讨论】:
-
请发布更多关于你得到的确切异常的信息,包括异常的类型、异常消息以及它在代码中发生的确切位置。
-
我现在已经附上了它的截图
-
使用 ListView lv= (ListView) rootView.findViewById(R.id.list);而不是你在 Fragment 中实现的任何东西的 getActivity
-
但是那行没有抛出异常
-
@Aashir its st.close()
标签: android listview jdbc navigation-drawer