我有一个列表片段,我试图将解析后的数据显示在列表视图中。应用程序不会崩溃,解析后的数据会出现在日志中,而不会出现在设备或模拟器上。有人可以帮忙吗?
public class FragmentOne extends ListFragment {
public static final String IMAGE_RESOURCE_ID = "iconResourceID";
public static final String ITEM_NAME = "itemName";
EditText editText;
Button sendBtn;
// Progress Dialog
private ProgressDialog pDialog;
//Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> messagesList;
//url to create new post
private static final String url_post_message = "http://example.com/database/folder/myscript.php";
//url to get all messages
private static String url_view_post = "http://example.com/database/folder/myscript.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PID = "pid";
private static final String TAG_MESSAGES = "messages";
//messages JSONArray
JSONArray messages = null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_layout_one,container, false);
editText = (EditText) view.findViewById(R.id.editText);
sendBtn = (Button) view.findViewById(R.id.sendBtn);
// button click event
sendBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
// creating new post in background thread
new Post().execute();
}
});
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Hashmap for ListView
messagesList = new ArrayList<HashMap<String, String>>();
// Loading messages in Background Thread
new ViewMessages().execute();
// Get listview
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
}});
}
//Background Async Task to Create new post
类Post扩展了AsyncTask {
//Before starting background thread Show Progress Dialog
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Posting..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
//Creating post
protected String doInBackground(String... args) {
String messages = editText.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("messages", messages));
// getting JSON Object
// Note that create post url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_post_message,
"POST", params);
// check log cat for response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created post
} else {
// failed to create post
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
// After completing background task Dismiss the progress dialog
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
/ ** * Background Async Task通过发出HTTP请求来查看所有消息 * * / class ViewMessages扩展了AsyncTask {
//getting all messages from url
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(url_view_post, "GET", params);
// Check your log cat for JSON reponse
Log.d("Messages:", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// messages found
// Getting Array of messages
messages = json.getJSONArray(TAG_MESSAGES);
// looping through all messages
for (int i = 0; i < messages.length(); i++) {
JSONObject c = messages.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String messages = c.getString(TAG_MESSAGES);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_MESSAGES, messages);
// adding HashList to ArrayList
messagesList.add(map);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
//Updating parsed JSON data into ListView
`ListAdapter adapter = new SimpleAdapter(getActivity(), messagesList,` R.layout.list_item, new String[]
{ TAG_PID, TAG_MESSAGES}, new int[] { R.id.pid, R.id.messages});
// updating listview
setListAdapter(adapter);
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/linearLayout1"
android:layout_marginTop="27dp" />
<TextView
android:id="@+id/pid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/messages"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
<Button
android:id="@+id/sendBtn"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="16dp"
android:layout_marginRight="19dp"
android:text="Button" />
<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/sendBtn"
android:layout_weight="1"
android:ems="10" />
</RelativeLayout>
答案 0 :(得分:0)
试试这个并确认我的回答谢谢你:)
将json字符串传递给此方法。它会起作用
public JSONObject getJSONfromURL(String url)
{
InputStream is = null;
JSONObject jObj = null;
String json = "";
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpget= new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpget);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (Exception e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
答案 1 :(得分:0)
搞定了!问题不在于我的Json是我需要为我的数据库中的表创建一个节点名称并更改JsonArray名称和for循环以匹配。 (消息实际上是我数据库的post表中的一行)