I have a list fragment where I'm trying to get parsed data to display in a list view. The app does not crash and the parsed data does appear in the log cat just not on the device or emulator. Can anyone help?
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
class Post extends 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 to view all messages by making HTTP Request * */ class ViewMessages extends 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>
Try this one and confirm my answer thank you :)
pass json string to this method . it will work
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;
}