Where do I put the function to display the loading process? - java

I want to display a loading process when my application is loading data from the database.
This is my Java file.
Where do I have to put the function to display the loading process?
public class AksesServerActivity extends ListActivity {
private static String link_url = "http://plnskh.zz.mu/android/berita/cekdaftar.php";
private static final String AR_ID = "id";
private static final String AR_JUDUL = "judul";
private static final String AR_CONTENT = "content";
JSONArray artikel = null;
ArrayList<HashMap<String, String>> daftar_artikel = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(link_url);
try {
artikel = json.getJSONArray("artikel");
for(int i = 0; i < artikel.length(); i++){
JSONObject ar = artikel.getJSONObject(i);
String id = ar.getString(AR_ID);
String judul = ar.getString(AR_JUDUL);
String content = ar.getString(AR_CONTENT).substring(0,100)+"...(baca selengkapnya)";
HashMap<String, String> map = new HashMap<String, String>();
map.put(AR_ID, id);
map.put(AR_JUDUL, judul);
map.put(AR_CONTENT, content);
daftar_artikel.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
this.adapter_listview();
}
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, daftar_artikel,
R.layout.list_item,
new String[] { AR_JUDUL, AR_CONTENT, AR_ID}, new int[] {
R.id.judul, R.id.content, R.id.kode});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String kode = ((TextView) view.findViewById(R.id.kode)).getText().toString();
Intent in = new Intent(AksesServerActivity.this, DetailAksesServer.class);
in.putExtra(AR_ID, kode);
startActivity(in);
}
});
}
}

public class LongOperation extends AsyncTask<String, String, String>
{
ProgressDialog pdialog;
#Override
protected String doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(link_url);
try {
artikel = json.getJSONArray("artikel");
for(int i = 0; i < artikel.length(); i++){
JSONObject ar = artikel.getJSONObject(i);
String id = ar.getString(AR_ID);
String judul = ar.getString(AR_JUDUL);
String content = ar.getString(AR_CONTENT).substring(0,100)+"...(baca selengkapnya)";
HashMap<String, String> map = new HashMap<String, String>();
map.put(AR_ID, id);
map.put(AR_JUDUL, judul);
map.put(AR_CONTENT, content);
daftar_artikel.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pdialog.dismiss();
this.adapter_listview();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pdialog = new ProgressDialog(NewsActivity.this);
pdialog.setMessage("Loading");
pdialog.show();
}
}
for more clarification about asynchronous task and its methods, check here

You must use AsyncTask class, override doInBackground method to perform your databse fetch, onPreExecute method to show your loading and onPostExecute to hide it. you can refer AsynTask process and AsynTask post for more information

Related

getting a error with my code private void update list everything from "this, mCommentList" is underlined in red

Could someone help me. I was following a very long tutorial and got to the end and can't fix this error. Starting at public void update list the code below is underlined in red and I can't seem to correct the problem.
public class readComments extends ListActivity {
private ProgressDialog pDialog;
private static final String READ_COMMENTS_URL = "http://120.120.1.100 /webservice/comments.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_TITLE = "title";
private static final String TAG_POSTS = "posts";
private static final String TAG_POST_ID = "post_id";
private static final String TAG_USERNAME = "username";
private static final String TAG_MESSAGE = "message";
private JSONArray mComments = null;
private ArrayList<HashMap<String, String>> mCommentList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.read_comments);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//loading the comments via AsyncTask
new LoadComments().execute();
}
public void addComment(View v)
{
Intent i = new Intent(readComments.this, AddComment.class);
startActivity(i);
}
public void updateJSONdata() {
}
private void updateList() {
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(readComments.this);
pDialog.setMessage("Loading Comments...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
try {
mComments = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_MESSAGE);
String username = c.getString(TAG_USERNAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
mCommentList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
//Problem starts here everything underlined in red
#Override
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.single_post, new String[]{TAG_TITLE, TAG_MESSAGE,
TAG_USERNAME}, new int[]{R.id.title, R.id.message,
R.id.username});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}

How to display the data from mySQL in listview in android?

I can insert data into database but now face the problem that cannot retrieve data from the database and display in listview in android. Here is my coding part for retrieve data. Hope someone can help to solve this, thank you.
package com.example.iuum;
private ProgressDialog pDialog;
private static final String READ_COMMENTS_URL = "http://10.19.229.212/webservice/comments.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_TITLE = "title";
private static final String TAG_POSTS = "posts";
private static final String TAG_POST_ID = "post_id";
private static final String TAG_USERNAME = "username";
private static final String TAG_MESSAGE = "message";
private JSONArray mComments = null;
private ArrayList<HashMap<String, String>> mCommentList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forum1a);
}
#Override
protected void onResume() {
super.onResume();
new LoadComments().execute();
}
public void clickbtnWrite(View v) {
Intent i = new Intent(Forum1a.this, AddForum.class);
startActivity(i);
}
/**
* Retrieves recent post data from the server.
*/
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
try {
mComments = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
// gets the content of each tag
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_MESSAGE);
String username = c.getString(TAG_USERNAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
mCommentList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.singelpost, new String[] { TAG_TITLE, TAG_MESSAGE,
TAG_USERNAME }, new int[] { R.id.title, R.id.message,
R.id.username });
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Forum1a.this);
pDialog.setMessage("Loading Comments...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
Add ListView in activity_forum1a.xml
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>
Take ListView reference
private ListView mList;
Initialize it in onCreate
mList = (ListView) findViewById(R.id.list_view);
Take ListAdapter class Refernce
private ListAdapter listAdapter;
Add setListAdapter method
public void setListAdapter(ListAdapter listAdapter) {
this.listAdapter = listAdapter;
mList.setAdapter(listAdapter);
}
Change updateList method to
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.test, new String[] { TAG_TITLE, TAG_MESSAGE,
TAG_USERNAME }, new int[] { R.id.title, R.id.message,
R.id.username });
setListAdapter(adapter);
}
and perform item click operation outside from the method, by implementing onItemClickListener

how to display details of single item of list in another activity from url (json data)?

I have written a program to display the list of json data from a url which has an image and 5 textviews which is displaying perfectly.
Url : https://itunes.apple.com/search?term=jack+johnson&limit=50.
When i click on an item from the list i want to display the details of that item in another activity based on the track-id
Url : https://itunes.apple.com/lookup?id=659234741
So when i click on the item the details are getting displayed in the textview , but by default it is displaying the details of id = 659234741 for some items or in short the details does not match.
Need some help to figure out the problem
My Code :
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultsList = new ArrayList<HashMap<String, String>>();
lv = getListView();
// Calling async task to get json
new GetTunesDetails().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetTunesDetails extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
tunes = jsonObj.getJSONArray(TAG_RESULT);
// looping through All Products
for (int i = 0; i < tunes.length(); i++) {
JSONObject c = tunes.getJSONObject(i);
artworkImage = c.getString("artworkUrl100");
wrapperType = c.getString("wrapperType");
artistName = c.getString("artistName");
collectionName = c.getString("collectionName");
trackName = c.getString("trackName");
collectionPrice = c.getString("collectionPrice");
trackId = c.getString("trackId");
// tmp hashmap for single contact
HashMap<String, String> tunesMap = new HashMap<String,
String>();
// adding each child node to HashMap key => value
// contact.put(TAG_ID, firstname);
tunesMap.put(TAG_ARTWORK_IMAGE, artworkImage);
tunesMap.put(TAG_WRAPPER_TYPE, wrapperType);
tunesMap.put(TAG_ARTIST_NAME, artistName);
tunesMap.put(TAG_COLLECTION_NAME, collectionName);
tunesMap.put(TAG_TRACK_NAME, trackName);
tunesMap.put(TAG_COLLECTION_PRICE, collectionPrice);
tunesMap.put(TAG_TRACK_ID, trackId);
// adding contact to contact list
resultsList.add(tunesMap);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, resultsList);
// Set the adapter to the ListView
lv.setAdapter(adapter);
}
}
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
int position;
TextView wrapperType, artistName, collectionName, trackName,
collectionPrice;
ImageView artworkImage;
public ListViewAdapter(Context context, ArrayList<HashMap<String, String>>
arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
// this.position = position;
inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.custom_row, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
wrapperType = (TextView) itemView.findViewById(R.id.wrapperType);
artistName = (TextView) itemView.findViewById(R.id.artistName);
collectionName = (TextView) itemView.findViewById(R.id.collectionName);
trackName = (TextView) itemView.findViewById(R.id.trackName);
collectionPrice = (TextView)
itemView.findViewById(R.id.collectionPrice);
// Locate the ImageView in listview_item.xml
artworkImage = (ImageView) itemView.findViewById(R.id.artworkImage);
// Capture position and set results to the TextViews
wrapperType.setText(resultp.get(MainActivity.TAG_WRAPPER_TYPE));
artistName.setText(resultp.get(MainActivity.TAG_ARTIST_NAME));
collectionName.setText(resultp.get(MainActivity.TAG_COLLECTION_NAME));
trackName.setText(resultp.get(MainActivity.TAG_TRACK_NAME));
collectionPrice.setText(resultp.get(MainActivity.TAG_COLLECTION_PRICE));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.TAG_ARTWORK_IMAGE),
artworkImage);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) { // TODO Auto-generated method
Toast.makeText(context, "Clicked at position " + position,
Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, SingleTrack.class);
intent.putExtra("track_image",
resultp.get(MainActivity.TAG_ARTWORK_IMAGE));
intent.putExtra("wrapper_type",
resultp.get(MainActivity.TAG_WRAPPER_TYPE));
intent.putExtra("artistName",
resultp.get(MainActivity.TAG_ARTIST_NAME));
intent.putExtra("collectionName",
resultp.get(MainActivity.TAG_COLLECTION_NAME));
intent.putExtra("trackName",
resultp.get(MainActivity.TAG_TRACK_NAME));
intent.putExtra("collectionPrice",
resultp.get(MainActivity.TAG_COLLECTION_PRICE));
intent.putExtra("trackId",
resultp.get(MainActivity.TAG_TRACK_ID));
context.startActivity(intent);
}
});
return itemView;
}
SingleTrack.java : This is the class where i displaying the details on single item click
public class SingleTrack extends Activity {
// URL to get contacts JSON
private static String url = "";
// JSON Node names
static final String TAG_RESULT = "results";
static final String TAG_ARTWORK_IMAGE = "artworkUrl100";
static final String TAG_WRAPPER_TYPE = "wrapperType";
static final String TAG_ARTIST_NAME = "artistName";
static final String TAG_COLLECTION_NAME = "collectionName";
static final String TAG_TRACK_NAME = "trackName";
static final String TAG_COLLECTION_PRICE = "collectionPrice";
static final String TAG_TRACK_ID = "trackId";
// contacts JSONArray
JSONArray tracks = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> singleTrackDetails;
ProgressDialog pDialog;
String passedData1, passedData2, passedData3, passedData4, passedData5,
passedData6, passedData7;
TextView wrapperTypeText, artistNameText, collectionNameText, trackNameText,
collectionPriceText;
ImageView trackImage;
String artworkImage, wrapperType, artistName, collectionName, trackName,
collectionPrice, trackId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.single_track);
wrapperTypeText = (TextView) findViewById(R.id.wrapperType1);
artistNameText = (TextView) findViewById(R.id.artistName1);
collectionNameText = (TextView) findViewById(R.id.collectionName1);
trackNameText = (TextView) findViewById(R.id.trackName1);
collectionPriceText = (TextView) findViewById(R.id.collectionPrice);
trackImage = (ImageView) findViewById(R.id.artworkImage1);
passedData1 = getIntent().getStringExtra("track_image");
passedData2 = getIntent().getStringExtra("wrapper_type");
passedData3 = getIntent().getStringExtra("artistName");
passedData4 = getIntent().getStringExtra("collectionName");
passedData5 = getIntent().getStringExtra("trackName");
passedData6 = getIntent().getStringExtra("collectionPrice");
passedData7 = getIntent().getStringExtra("trackId");
singleTrackDetails = new ArrayList<HashMap<String, String>>();
// url
url = "https://itunes.apple.com/lookup?id=" + passedData7;
// Calling async task to get json
new GetSingleTrackDetails().execute();
}
class GetSingleTrackDetails extends AsyncTask<String, Void, String> {
private JSONObject jsonObj;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SingleTrack.this);
pDialog.setMessage("Loading Track Details...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
tracks = jsonObj.getJSONArray(TAG_RESULT);
// looping through All Products
for (int i = 0; i < tracks.length(); i++) {
JSONObject c = tracks.getJSONObject(i);
artworkImage = c.getString("artworkUrl100");
wrapperType = c.getString("wrapperType");
artistName = c.getString("artistName");
collectionName = c.getString("collectionName");
trackName = c.getString("trackName");
collectionPrice = c.getString("collectionPrice");
trackId = c.getString("trackId");
// tmp hashmap for single contact
HashMap<String, String> tunesMap = new HashMap<String,
String>();
// adding each child node to HashMap key => value
// contact.put(TAG_ID, firstname);
tunesMap.put(TAG_ARTWORK_IMAGE, artworkImage);
tunesMap.put(TAG_WRAPPER_TYPE, wrapperType);
tunesMap.put(TAG_ARTIST_NAME, artistName);
tunesMap.put(TAG_COLLECTION_NAME, collectionName);
tunesMap.put(TAG_TRACK_NAME, trackName);
tunesMap.put(TAG_COLLECTION_PRICE, collectionPrice);
tunesMap.put(TAG_TRACK_ID, trackId);
// adding contact to contact list
singleTrackDetails.add(tunesMap);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
wrapperTypeText.setText(wrapperType);
artistNameText.setText(artistName);
collectionNameText.setText(collectionName);
trackNameText.setText(trackName);
collectionPriceText.setText(collectionPrice);
}
}
Thank you
The problem is that you are initializing the resultp each element in your getView method, so therefore the last id/element of the listview adapter's data will be considered as the resultp.
Im sure that the id 659234741 is the last element, which will always be the id for each onclick that would happen.
A solution for this is to create a final resultp within your getView method instead of having just one global resultp.
final HashMap<String, String> resultp = data.get(position);

Base Adapter in Asynctask not working

I am working with facebook app for my project and I'm getting a json from the graph API. I have a custom listView with hashMap, but when I run, the list wont populate but there isn't any errors. please help me.
here are the codes:
public class PageFeedHome extends Fragment {
ArrayList<HashMap<String, String>> feedList;
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_MESSAGE = "message";
private String feedMessage;
ListView listView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.feed_home_activity,
container, false);
listView = (ListView) view.findViewById(R.id.feed_lv);
feedList = new ArrayList<HashMap<String, String>>();
new LoadPosts().execute();
BaseAdapter adapter = new SimpleAdapter(getActivity(), feedList,
R.layout.feed_item_view, new String[] { TAG_MESSAGE, TAG_NAME,
TAG_ID }, new int[] { R.id.message, R.id.author,
R.id.id_tv });
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return view;
}
private class LoadPosts extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Session.openActiveSession(getActivity(), true,
new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
new Request(session, "/163340583656/feed",
null, HttpMethod.GET,
new Request.Callback() {
public void onCompleted(
Response response) {
/* handle the result */
Log.i("PostFeedResponse", response.toString());
try {
GraphObject graphObj = response
.getGraphObject();
JSONObject json = graphObj
.getInnerJSONObject();
JSONArray jArray = json
.getJSONArray("data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject currObj = jArray.getJSONObject(i);
final String feedId = currObj.getString("id");
if (currObj.has("message")) {
feedMessage = currObj.getString("message");
} else if (currObj.has("story")) {
feedMessage = currObj.getString("story");
} else {
feedMessage = "Posted a something";
}
JSONObject fromObj = currObj.getJSONObject("from");
String from = fromObj.getString("name");
HashMap<String, String> feed = new HashMap<String, String>();
feed.put(TAG_ID, feedId);
feed.put(TAG_MESSAGE, feedMessage);
feed.put(TAG_NAME, from);
feedList.add(feed);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).executeAsync();
}
}
});
return null;
}
}
}
Move this code :
BaseAdapter adapter = new SimpleAdapter(getActivity(), feedList,
R.layout.feed_item_view, new String[] { TAG_MESSAGE, TAG_NAME,
TAG_ID }, new int[] { R.id.message, R.id.author,
R.id.id_tv }); //initialize adapter
listView.setAdapter(adapter); //set adapter
adapter.notifyDataSetChanged();
To the AsyncTask's onPostExecute to make sure the feedList is already inserted from the onBackground.
Or if you prefer to initialize your adapter and setting the adapter to the listview in the onCreate, just move adapter.notifyDataSetChanged(); to the onPostExecute. This is recommended if you call the AsyncTask multiple times, because theres no need to initialize and set the adapter multiple times. (see my comment in the code)
ArrayList<HashMap<String, String>> feedList;
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_MESSAGE = "message";
private String feedMessage;
ListView listView;
BaseAdapter adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.feed_home_activity,
container, false);
listView = (ListView) view.findViewById(R.id.feed_lv);
feedList = new ArrayList<HashMap<String, String>>();
BaseAdapter adapter = new SimpleAdapter(getActivity(), feedList,
R.layout.feed_item_view, new String[] { TAG_MESSAGE, TAG_NAME,
TAG_ID }, new int[] { R.id.message, R.id.author,
R.id.id_tv });
listView.setAdapter(adapter);
new LoadPosts().execute();
return view;
}
private class LoadPosts extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Session.openActiveSession(getActivity(), true,
new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
new Request(session, "/163340583656/feed",
null, HttpMethod.GET,
new Request.Callback() {
public void onCompleted(
Response response) {
/* handle the result */
Log.i("PostFeedResponse", response.toString());
try {
GraphObject graphObj = response
.getGraphObject();
JSONObject json = graphObj
.getInnerJSONObject();
JSONArray jArray = json
.getJSONArray("data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject currObj = jArray.getJSONObject(i);
final String feedId = currObj.getString("id");
if (currObj.has("message")) {
feedMessage = currObj.getString("message");
} else if (currObj.has("story")) {
feedMessage = currObj.getString("story");
} else {
feedMessage = "Posted a something";
}
JSONObject fromObj = currObj.getJSONObject("from");
String from = fromObj.getString("name");
HashMap<String, String> feed = new HashMap<String, String>();
feed.put(TAG_ID, feedId);
feed.put(TAG_MESSAGE, feedMessage);
feed.put(TAG_NAME, from);
feedList.add(feed);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).executeAsync();
}
}
});
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), ""+feedList.size(), Toast.LENGTH_LONG).show();
adapter.notifyDataSetChanged();
}
}
}

Parse Json Object in android?

I am developing one application in that i have to receive data from server ,I am successfully read data . here i have problem i receive data from server code wrote in AsyncTask,and send data from AsyncTask to My activity,here i send only one data out of three,my json object have 3 objects.i can get 3 objects in AsyncTask but not getting in Activity
my AsyncTask
public class ReceivingLatLongAsync extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;
Context mContext;
JSONArray jsonArryDetails=null;
public static final String DETAILS = "locations";
public static final String LAT = "lat";
public static final String LNG = "lng";
public static final String ADDRESS = "address";
public static final String CTIME = "ctime";
private String lat1;
private String lng1;
private String address1;
private String time1;
public ReceivingLatLongAsync(Context context){
this.mContext = context;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(mContext);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
ServiceHandler serviceHandler= new ServiceHandler();
String jSonString = `serviceHandler.makeServiceCall
(TrafficConstants.RECIEVE_LATLON_POL_URL, ServiceHandler.POST);`
Log.e("Response: ", "> " + jSonString);
if(jSonString != null){
try {
JSONObject jsonObject = new JSONObject(jSonString);
jsonArryDetails = jsonObject.getJSONArray(DETAILS);
for(int i = 0;i<jsonArryDetails.length();i++){
JSONObject mapDetails =
jsonArryDetails.getJSONObject(0);
lat1 = mapDetails.getString(LAT);
lng1 = mapDetails.getString(LNG);
address1 = mapDetails.getString(ADDRESS);
time1 = mapDetails.getString(CTIME);
Log.e("ADDRESS1", address1);
Log.e("TIME2",time1);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pDialog.dismiss();
Intent intent = new Intent(mContext,GetLatLongForTPActivity.class);
intent.putExtra("LAT", lat1);
intent.putExtra("LNG", lng1);
intent.putExtra("ADDRESS", address1);
intent.putExtra("time",time1);
mContext.startActivity(intent);
}
}
my activty
public class GetLatLongForTPActivity extends FragmentActivity
implements LocationListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_lat_long_for_tp);
timeEdit = (EditText)findViewById(R.id.timeId);
submitBtn = (Button)findViewById(R.id.subId);
Intent intent = getIntent();
String anotherLAT=intent.getStringExtra("LAT");
String anotherLNG=intent.getStringExtra("LNG");
Log.e(" NEW LATLONG",anotherLAT);
}
Becouse it is an jsonArray and now you send only the last object not the entier array
Change this
JSONObject mapDetails =
jsonArryDetails.getJSONObject(0);
to
JSONObject mapDetails =
jsonArryDetails.getJSONObject(i);
You have to add something like
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
for(int i = 0;i<jsonArryDetails.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject mapDetails =
jsonArryDetails.getJSONObject(i);
lat1 = mapDetails.getString(LAT);
lng1 = mapDetails.getString(LNG);
address1 = mapDetails.getString(ADDRESS);
time1 = mapDetails.getString(CTIME);
map.put(LAT, lat1);
map.put(LNG, lg1);
map.put(ADDRESS, address1 );
map.put(CTIME, time1 );
mylist.add(map);
}
In for loop change the index :
for(int i = 0;i<jsonArryDetails.length();i++){
JSONObject mapDetails =jsonArryDetails.getJSONObject(i);
//etc ^ //change here
You need to create a class that stores the four fields you are using (lat,long,address,time), make that object parable, you could use this example: http://aryo.lecture.ub.ac.id/android-passing-arraylist-of-object-within-an-intent/ ;
And after that you can attach the array to the intent using:
intent.putParcelableArrayListExtra(String name, ArrayList<? extends Parcelable> value)
This would be the correct way to handle this, even if it's a little more complicated then you originally would have hoped.

Categories

Resources