我是android的新手,我使用的是mysql数据库,我在那里链接php文件进行连接,这很好,但我的代码没有显示任何内容,它只显示黑色背景,而不是显示数据库的数据
public class HomeFragment extends Fragment {
GridView gv;
@SuppressLint("NewApi")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home, container, false);
StrictMode.enableDefaults();
gv = (GridView) rootView.findViewById(R.id.gridView_home);
getData();
return rootView;
}
public void getData(){
String result = "";
InputStream isr = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.2/Android/App/getcu.php"); //YOUR PHP SCRIPT ADDRESS
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
gv.setFilterText("Couldnt connect to database "+ e.getMessage()); //not printing anything
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "'n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
s = s +
"Name : "+json.getString("FirstName")+" "+json.getString("LastName")+"'n"+
"Age : "+json.getInt("Age")+"'n"+
"Mobile Using : "+json.getString("Mobile")+"'n'n";//+
"Artist:"+json.put("Images",true ); // not printing anything
}
gv.setFilterText(s); // not printing showing empty
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString()); }
} }
从文件夹Android/pictures/image1json检索图像时又出现一个错误,即没有打印部署到数据库中的特定图像
"Artist:"+json.put("Images",true );
使用json检索图像的上述语句正确吗?或者我必须更正
请帮助我更正上面的程序,感谢您宝贵的时间。我不明白为什么它没有打印任何东西,但当我将其扩展到活动时,它正在工作。如何在片段中使用它
好的,为了避免添加更多注释:
-
确保
result
字符串中有正确的JSON数据。日志记录可以帮助完成这样的任务。或者只使用Toast
来显示字符串,以验证其正确性。 -
gv.setFilterText(s);
将不会导致任何输出。要在GUI中显示字符串,您应该使用一个TextView
项目,将放入布局中,在本例中为GridView
,在其上为setText()
。