Adding new item on top of listview - android

When i insert my parsed data into the listview, the added items appear at the bottom i want to put them on top like on facebook new posts are added on top. here is my code:
I am retrieving my comments from a server. Pls help me out
This is the Readpost.java
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.newsfeed);
}
#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(Readpost.this, Addpost.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);
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();
}
}
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.singlepost, 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.scrollTo(0, 0);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
And this is the Addpost.java
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addpost);
title = (EditText)findViewById(R.id.title);
message = (EditText)findViewById(R.id.message);
mSubmit = (Button)findViewById(R.id.submit);
mSubmit.setOnClickListener(this);
}
#Override
public void onClick(View v) {
new PostComment().execute();
}
class PostComment extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Addpost.this);
pDialog.setMessage("Posting...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String post_title = title.getText().toString();
String post_message = message.getText().toString();
try {
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String value =(mSharedPreference.getString("username", "anon"));
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", value));
params.add(new BasicNameValuePair("title", post_title));
params.add(new BasicNameValuePair("message", post_message));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(
POST_COMMENT_URL, "POST", params);
Log.d("Post Comment attempt", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Comment Added!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Comment Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Addpost.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}

Assuming you retain your ListAdapter as follows:
ListAdapter mAdapter;
You can add a new item like this.
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, "New Title");
map.put(TAG_MESSAGE, "new content");
map.put(TAG_USERNAME, "someone");
mCommentList.add(0, map);
mAdapter.notifyDatasetChanged();

Use this:
mCommentList.add(0, obj);
listAdapter.notifyDataSetChanged();
listView.scrollTo(0, 0);

Related

How to Show JSON DATA in LISTVIEW

I have a JSON data from YouTube. I want to show data in LIST VIEW. But when i run my code I get a blank page. But I have the respond of YouTube DATA API. How can I solve it?
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "https://www.googleapis.com/youtube/v3/search?part=snippet&maxResult=30&q=natok+bangla+mosharrof+karim&key=AIzaSyCR40QlsuX0aFfBV-wEPDsH_jxna1tDFRA";
private static final String TAG_ITEMS = "items";
private static final String TAG_ID = "id";
private static final String TAG_ID_VIDEOID = "vid";
private static final String TAG_TITLE = "title";
private static final String TAG_DESCRIPTION = "description";
private static final String YouTubeThumbnail = "https://i.ytimg.com/vi/hlaX2OZ_kDg/default.jpg";
private static final String TAG_CHANNELTITLE = "channelTitle";
JSONArray items = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String vid = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String title = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_ID_VIDEOID, vid);
in.putExtra(TAG_TITLE, title);
in.putExtra(TAG_DESCRIPTION, description);
startActivity(in);
}
});
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Boolean> {
#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 Boolean doInBackground(Void... arg0) {
// 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);
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String,String>>();
int count = 0;
try {
JSONObject js = new JSONObject(jsonStr);
JSONArray jsItem = js.getJSONArray("items");
for (int i = 0; i < jsItem.length(); i++) {
JSONObject item = jsItem.getJSONObject(i);
JSONObject vid =item.getJSONObject("id");
String videoId = getStringResult(vid.toString(), "videoId");
if (!videoId.equalsIgnoreCase(""))
{
JSONObject snippet =item.getJSONObject("snippet");
String title = sh.getStringResult(snippet.toString(), "title");
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", title);
map.put("vid", videoId);
map.put ("img","http://img.youtube.com/vi/" + videoId + "/hqdefault.jpg");
map.put ("id",++count+"");
dataList.add(map);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, dataList,R.layout.list_item, new String[] { TAG_TITLE, TAG_DESCRIPTION,
TAG_CHANNELTITLE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
public String getStringResult(String data, String node) {
try {
JSONObject js = new JSONObject(data);
return js.getString(node);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
Use notifyDataSetChanged(). This notifies a change in data and updated the list view. LINK
Here are the changes that would help:
public class MainActivity extends ListActivity {
...
ListAdapter adapter = null;
#Override
public void onCreate(Bundle savedInstanceState) {
...
ListView lv = getListView();
adapter = new SimpleAdapter(
MainActivity.this, dataList,R.layout.list_item, new String[] { TAG_TITLE, TAG_DESCRIPTION,
TAG_CHANNELTITLE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
lv.setListAdapter(adapter);
...
}
private class GetContacts extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
...
}
#Override
protected Boolean doInBackground(Void... arg0) {
...
}
#Override
protected void onPostExecute(Boolean result) {
if(adapter ! = null) {
adapter.notifyDataSetChanged();
}
}
public String getStringResult(String data, String node) {
...
}
Explanation:
ListAdapter is the bridge between a ListView and the data that backs the list.
Whenever the data is changed, adapter is responsible to notify about the changed data and consequently the view gets updated with the new data. This is achieved by notifyDataSetChanged().
For some more details, please go through this link.

How to Listview with image ? Anyone have any idea how to do that using this code

I already try to display image in ListView, but I got an error at this line:
status.setImageResource(R.drawable.inprogress);
*setimageresource undefined for String.
I'm trying to display the image based on the status, if status equals to "Compalint in process" and then the in progress icon will display in the ListView.
This my full code:
public class SenaraiSemuaComplaint extends ListActivity {
String stud_staff_ID;
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> listcomplaint;
final Context context = this;
private static String url_listcomplaint = "...";
private static final String TAG_SUCCESS = "success";
private static final String TAG_REGISTER = "register";
private static final String TAG_PID = "pid";
private static final String TAG_DATE = "date";
private static final String TAG_STATUS = "status";
JSONArray register = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listallcomplaint_layout);
getActionBar().setHomeButtonEnabled(true);
String input = getIntent().getStringExtra("stud_staff_ID");
Toast.makeText(this, input, Toast.LENGTH_SHORT).show();
listcomplaint = new ArrayList<HashMap<String, String>>();
new LoadAllComplaint().execute();
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
String location = ((TextView) view.findViewById(R.id.location)).getText()
.toString();
String picture = ((TextView) view.findViewById(R.id.picture)).getText()
.toString();
String input = getIntent().getStringExtra("stud_staff_ID");
Intent in = new Intent(getApplicationContext(),
ViewPage.class);
in.putExtra("location", location);
in.putExtra("picture", picture);
in.putExtra("stud_staff_ID", input);
in.putExtra("pid", pid);
startActivityForResult(in, 100);
}
});
}
public boolean onOptionsItemSelected(MenuItem item){
if(android.R.id.home == item.getItemId()){
finish();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class LoadAllComplaint extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SenaraiSemuaComplaint.this);
pDialog.setMessage("Please wait, Loading Data...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
String input = getIntent().getStringExtra("stud_staff_ID");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("input", input));
JSONObject json = jParser.makeHttpRequest(url_listcomplaint, "GET", params);
Log.d("List Complaint: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
register = json.getJSONArray(TAG_REGISTER);
for (int i = 0; i < register.length(); i++) {
JSONObject c = register.getJSONObject(i);
// keep to variable
String pid = c.getString(TAG_PID);
String date = c.getString(TAG_DATE);
String status = c.getString(TAG_STATUS);
if (status.equals("Complaint in process."))
{
status.setImageResource(R.drawable.inprogress);
}
String location = c.getString("location");
String picture = c.getString("picture");
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_PID, pid);
map.put(TAG_DATE, date);
map.put(TAG_STATUS, status);
map.put("location", location);
map.put("picutre", picture);
listcomplaint.add(map);
}
} else {
runOnUiThread(new Runnable()
{
public void run(){
String msgs = "No complaint found, please create new complaint.";
Toast.makeText(getApplicationContext(), msgs, Toast.LENGTH_SHORT).show();
}
});
String i = getIntent().getStringExtra("stud_staff_ID");
Intent in12 = new Intent(getApplicationContext(),ComplaintBaru.class);
in12.putExtra("stud_staff_ID", i);
startActivity(in12);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
SenaraiSemuaComplaint.this, listcomplaint,
R.layout.list_pendaftaran, new String[] {TAG_PID,
TAG_DATE, TAG_STATUS, "location", "picture" },
new int[] {R.id.pid, R.id.inputDate, R.id.inputStatus, R.id.location, R.id.picture});
setListAdapter(adapter);
}
});
}
}
}
I suggest judging by what you want to achieve that handle this in your Adapter for the ListView which would be the adapter you supply to the ListActivity.
In the getView() of your adapter check the value of your TextView and then replace it with a ProgressBar either dynamically or by toggling its visibility by letting it reside in the layout for your rows.
it's require to take ImageView than set to Image
Imageview img=(ImageView)findViewById(R.id.yourimageID).setImageResource(R.drawable.inprogress);

android from activity to fragment

I'm new to android. I want to put one of the activity under one of the tab of my app(the tab is fragment) when i paste my code into fragment, there's a lot of error...
There's error in new JSONParse().execute(); It shows that the type JSONParse is not visible.
in this line private class JSONParse extends AsyncTask there's error
showing illegal modifier for the class JSONParse.only public, abstract and final are permitted.
this line pDialog = new ProgressDialog(TabActivityQueue.this); it shows the constructor progressDialog is undefined.
All the variables phonenumber, peoplenumber , remarks, status, table2, url are not resolved as variables.
What should I change? I'm really stuck.
Here's the activity code :
public class MainActivity extends Activity {
ListView list;
TextView number;
TextView info;
TextView remark;
TextView statuss;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://172.22.85.235:8080/Qproject/servlet/Qaction?action_flag=find";
//JSON Node Names
private static final String Table2 = "table2";
private static final String phonenumber = "phonenumber";
private static final String peoplenumber = "peoplenumber";
private static final String remarks = "remarks";
private static final String status = "status";
JSONArray table2 = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
number = (TextView)findViewById(R.id.number);
info = (TextView)findViewById(R.id.info);
remark = (TextView)findViewById(R.id.remark);
statuss = (TextView)findViewById(R.id.statuss);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
table2 = json.getJSONArray(Table2);
for(int i = 0; i < table2.length(); i++){
JSONObject c = table2.getJSONObject(i);
// Storing JSON item in a Variable
String number = c.getString(phonenumber);
String info = c.getString(peoplenumber);
String remark = c.getString(remarks);
String statuss = c.getString(status);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(phonenumber, number);
map.put(peoplenumber, info);
map.put(remarks, remark);
map.put(status, statuss);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_item,
new String[] { phonenumber,peoplenumber, remarks,status }, new int[] {
R.id.number,R.id.info, R.id.remark,R.id.statuss});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here's the fragment where i pasted the activity code in :
public class TabActivityQueue extends Fragment {
ListView list;
TextView number;
TextView info;
TextView remark;
TextView statuss;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
public static String url = "http://172.22.85.235:8080/Qproject/servlet/Qaction?action_flag=find";
//JSON Node Names
public static final String Table2 = "table2";
public static final String phonenumber = "phonenumber";
public static final String peoplenumber = "peoplenumber";
public static final String remarks = "remarks";
public static final String status = "status";
JSONArray table2 = null;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
//This layout contains your list view
View view = inflater.inflate(R.layout.activity_tab_activity_queue, container, false);
oslist = new ArrayList<HashMap<String, String>>();
number = (TextView)view.findViewById(R.id.number);
info = (TextView)view.findViewById(R.id.info);
remark = (TextView)view.findViewById(R.id.remark);
statuss = (TextView)view.findViewById(R.id.statuss);
Btngetdata = (Button)view.findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
return view;
}
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TabActivityQueue.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
table2 = json.getJSONArray(Table2);
for(int i = 0; i < table2.length(); i++){
JSONObject c = table2.getJSONObject(i);
// Storing JSON item in a Variable
String number = c.getString(phonenumber);
String info = c.getString(peoplenumber);
String remark = c.getString(remarks);
String statuss = c.getString(status);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(phonenumber, number);
map.put(peoplenumber, info);
map.put(remarks, remark);
map.put(status, statuss);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_item,
new String[] { phonenumber,peoplenumber, remarks,status }, new int[] {
R.id.number,R.id.info, R.id.remark,R.id.statuss});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class TabActivityQueue extends Fragment {
ListView list;
TextView number;
TextView info;
TextView remark;
TextView statuss;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
// URL to get JSON Array
public static String url = "http://172.22.85.235:8080/Qproject/servlet/Qaction?action_flag=find";
// JSON Node Names
public static final String Table2 = "table2";
public static final String phonenumber = "phonenumber";
public static final String peoplenumber = "peoplenumber";
public static final String remarks = "remarks";
public static final String status = "status";
JSONArray table2 = null;
private Activity activity;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
// This layout contains your list view
View view = inflater.inflate(R.layout.activity_tab_activity_queue, container, false);
oslist = new ArrayList<HashMap<String, String>>();
number = (TextView) view.findViewById(R.id.number);
info = (TextView) view.findViewById(R.id.info);
remark = (TextView) view.findViewById(R.id.remark);
statuss = (TextView) view.findViewById(R.id.statuss);
Btngetdata = (Button) view.findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
activity = this.getActivity();
return view;
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(activity);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
table2 = json.getJSONArray(Table2);
for (int i = 0; i < table2.length(); i++) {
JSONObject c = table2.getJSONObject(i);
// Storing JSON item in a Variable
String number = c.getString(phonenumber);
String info = c.getString(peoplenumber);
String remark = c.getString(remarks);
String statuss = c.getString(status);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(phonenumber, number);
map.put(peoplenumber, info);
map.put(remarks, remark);
map.put(status, statuss);
oslist.add(map);
list = (ListView) findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(activity, oslist, R.layout.list_item, new String[] {phonenumber, peoplenumber, remarks, status}, new int[] {R.id.number, R.id.info,
R.id.remark, R.id.statuss});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(activity, "You Clicked at " + oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Whereever you have used context as TabActivityQueue.this (or getApplicationCOntext()) change to getActivity() .
Also if some android pre defined method doesn't work try prefix getActivity() like:- getActivity().method();
declare private Activity activity as public Activity activity;

Load page 2,3,4 in AsyncTask from JSON paginated file Android

I have a paginated JSON file where I have all my data. At the end of my url link, if you change the page number, it executes and lists next items like "?page=1" or "3,4,5,6".
By default its kept at "?page=0" which is the first page viewed when parsed in Android.
I have also added a footer view with a Button "LoadMore" which is seen at the end of the listview.
Now I wanted this LoadMore button to go to page 2 after clicking when I am at page 1 end. again to page 3, when I click LoadMore on page 2.
I am so confused of implementing it. This is my Asynic Task. Something to do in "doInBackground"
class LoadRestaurants extends AsyncTask<String, String, String> {
//Show Progress Dialog
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchAll.this);
pDialog.setMessage("Loading All Restaurants...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... arg) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
current_page = 0;
URL_RESTAURANT_LIST
= "http://www.petuuk.com/android/allRestaurantList3.php?page=" + current_page;
//Getting JSON from URL
String json = jsonParser.makeHttpRequest(URL_RESTAURANT_LIST, "GET", params);
//Log Cat Response Check
Log.d("Areas JSON: ", "> " + json);
try {
restaurants = new JSONArray(json);
if (restaurants != null) {
//loop through all restaurants
for (int i = 0; i < restaurants.length(); i++) {
JSONObject c = restaurants.getJSONObject(i);
//Storing each json object in the variable.
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String location = c.getString(TAG_LOCATION);
String rating = c.getString(TAG_RATING);
//Creating New Hashmap
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to Hashmap key
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_LOCATION, location);
map.put(TAG_RATING, rating);
//adding HashList to ArrayList
restaurant_list.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
//dismiss the dialog
pDialog.dismiss();
//Updating UI from the Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
ListAdapter adapter = new SimpleAdapter(
SearchAll.this, restaurant_list,
R.layout.listview_restaurants, new String[]{
TAG_ID, TAG_NAME, TAG_LOCATION, TAG_RATING}, new int[]{
R.id.login_id, R.id.restaurant_name, R.id.address, R.id.rating});
setListAdapter(adapter);
ListView lv = getListView();
int currentPosition = lv.getFirstVisiblePosition();
lv.setSelectionFromTop(currentPosition + 1, 1);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Bundle bundle = new Bundle();
Intent intent = new Intent(getApplicationContext(),RestaurantProfile.class);
String loginId = ((TextView) view.findViewById(R.id.login_id)).getText().toString();
String res_name = ((TextView)
view.findViewById(R.id.restaurant_name)).getText().toString();
intent.putExtra(TAG_ID, loginId);
intent.putExtra(TAG_NAME, res_name);
startActivity(intent);
}
});
}
});
}
}
This is my LoadMore Button code.
Button btnLoadMore = new Button(SearchAll.this);
btnLoadMore.setText("Show More");
getListView().addFooterView(btnLoadMore);
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
My searchAll file, where all the code goes.
public class SearchAll extends ListActivity {
ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
//Progress Dialog
private ProgressDialog pDialog;
//make json parser Object
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> restaurant_list;
//Restaurant Json array
JSONArray restaurants = null;
private String URL_RESTAURANT_LIST
= "http://www.petuuk.com/android/allRestaurantList3.php?page=0";
//all JSON Node Names
private static final String TAG_ID = "login_id";
private static final String TAG_NAME = "name";
private static final String TAG_LOCATION = "location";
private static final String TAG_RATING = "rating";
//Flag for current page
int current_page = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_all);
cd = new ConnectionDetector(getApplicationContext());
//Check for Internet Connection
if (!cd.isConnectingToInternet()) {
//Internet connection not present
alert.showAlertDialog(SearchAll.this, "Internet Connection Error",
"Please Check Your Internet Connection", false);
//stop executing code by return
return;
}
restaurant_list = new ArrayList<HashMap<String, String>>();
new LoadRestaurants().execute();
//new LoadRestaurants().execute();
Button btnLoadMore = new Button(SearchAll.this);
btnLoadMore.setText("Show More");
getListView().addFooterView(btnLoadMore);
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new LoadMore().execute();
}
});
}
class LoadRestaurants extends AsyncTask<String, String, String> {
//Show Progress Dialog
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchAll.this);
pDialog.setMessage("Loading All Restaurants...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... arg) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
URL_RESTAURANT_LIST
= "http://www.petuuk.com/android/allRestaurantList3.php?page=0";
//Getting JSON from URL
String json = jsonParser.makeHttpRequest(URL_RESTAURANT_LIST, "GET", params);
//Log Cat Response Check
Log.d("Areas JSON: ", "> " + json);
try {
restaurants = new JSONArray(json);
if (restaurants != null) {
//loop through all restaurants
for (int i = 0; i < restaurants.length(); i++) {
JSONObject c = restaurants.getJSONObject(i);
//Storing each json object in the variable.
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String location = c.getString(TAG_LOCATION);
String rating = c.getString(TAG_RATING);
//Creating New Hashmap
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to Hashmap key
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_LOCATION, location);
map.put(TAG_RATING, rating);
//adding HashList to ArrayList
restaurant_list.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
//dismiss the dialog
pDialog.dismiss();
//Updating UI from the Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
ListAdapter adapter = new SimpleAdapter(
SearchAll.this, restaurant_list,
R.layout.listview_restaurants, new String[]{
TAG_ID, TAG_NAME, TAG_LOCATION, TAG_RATING}, new int[]{
R.id.login_id, R.id.restaurant_name, R.id.address, R.id.rating});
setListAdapter(adapter);
ListView lv = getListView();
int currentPosition = lv.getFirstVisiblePosition();
lv.setSelectionFromTop(currentPosition + 1, 1);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Bundle bundle = new Bundle();
Intent intent = new Intent(getApplicationContext(), RestaurantProfile.class);
String loginId = ((TextView) view.findViewById(R.id.login_id)).getText().toString();
String res_name =((TextView) view.findViewById
(R.id.restaurant_name)).
getText().toString();
intent.putExtra(TAG_ID, loginId);
intent.putExtra(TAG_NAME, res_name);
startActivity(intent);
}
});
}
});
}
}
private class LoadMore extends AsyncTask<Void, Void, Void> {
//Show Progress Dialog
#Override
protected Void doInBackground(Void... voids) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
current_page = current_page + 1;
URL_RESTAURANT_LIST
= "http://www.petuuk.com/android/allRestaurantList3.php?page=" + current_page;
//Getting JSON from URL
String json = jsonParser.makeHttpRequest(URL_RESTAURANT_LIST, "GET", params);
//Log Cat Response Check
Log.d("Areas JSON: ", "> " + json);
try {
restaurants = new JSONArray(json);
if (restaurants != null) {
//loop through all restaurants
for (int i = 0; i < restaurants.length(); i++) {
JSONObject c = restaurants.getJSONObject(i);
//Storing each json object in the variable.
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String location = c.getString(TAG_LOCATION);
String rating = c.getString(TAG_RATING);
//Creating New Hashmap
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to Hashmap key
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_LOCATION, location);
map.put(TAG_RATING, rating);
//adding HashList to ArrayList
restaurant_list.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void unused) {
// closing progress dialog
pDialog.dismiss();
}
}
}
Finally got it working!
public class SearchAll extends ListActivity {
ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
//Progress Dialog
private ProgressDialog pDialog;
//make json parser Object
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> restaurant_list;
//Restaurant Json array
JSONArray restaurants = null;
private String URL_RESTAURANT_LIST
= "http://www.petuuk.com/android/allRestaurantList3.php?page=0";
//all JSON Node Names
private static final String TAG_ID = "login_id";
private static final String TAG_NAME = "name";
private static final String TAG_LOCATION = "location";
private static final String TAG_RATING = "rating";
//Flag for current page
// int current_page = 1;
int bCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_all);
cd = new ConnectionDetector(getApplicationContext());
//Check for Internet Connection
if (!cd.isConnectingToInternet()) {
//Internet connection not present
alert.showAlertDialog(SearchAll.this, "Internet Connection Error",
"Please Check Your Internet Connection", false);
//stop executing code by return
return;
}
restaurant_list = new ArrayList<HashMap<String, String>>();
new LoadRestaurants().execute();
//new LoadRestaurants().execute();
Button btnLoadMore = new Button(SearchAll.this);
btnLoadMore.setText("Show More");
getListView().addFooterView(btnLoadMore);
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bCount++;
new LoadRestaurants().execute();
}
});
}
class LoadRestaurants extends AsyncTask<String, String, String> {
//Show Progress Dialog
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchAll.this);
pDialog.setMessage("Loading All Restaurants...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... arg) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
URL_RESTAURANT_LIST
= "http://www.petuuk.com/android /allRestaurantList3.php?page=
" + bCount;
//Getting JSON from URL
String json = jsonParser.makeHttpRequest(URL_RESTAURANT_LIST, "GET", params);
//Log Cat Response Check
Log.d("Areas JSON: ", "> " + json);
try {
restaurants = new JSONArray(json);
if (restaurants != null) {
//loop through all restaurants
for (int i = 0; i < restaurants.length(); i++) {
JSONObject c = restaurants.getJSONObject(i);
//Storing each json object in the variable.
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String location = c.getString(TAG_LOCATION);
String rating = c.getString(TAG_RATING);
//Creating New Hashmap
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to Hashmap key
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_LOCATION, location);
map.put(TAG_RATING, rating);
//adding HashList to ArrayList
restaurant_list.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
//dismiss the dialog
pDialog.dismiss();
//Updating UI from the Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
ListAdapter adapter = new SimpleAdapter(
SearchAll.this, restaurant_list,
R.layout.listview_restaurants, new String[]{
TAG_ID, TAG_NAME, TAG_LOCATION, TAG_RATING}, new int[]{
R.id.login_id, R.id.restaurant_name, R.id.address, R.id.rating});
setListAdapter(adapter);
ListView lv = getListView();
int currentPosition = lv.getFirstVisiblePosition();
lv.setSelectionFromTop(currentPosition + 1, 1);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Bundle bundle = new Bundle();
Intent intent = new Intent(getApplicationContext(), RestaurantProfile.class);
String loginId = ((TextView) view.findViewById(R.id.login_id)).getText().toString();
String res_name = ((TextView) view.findViewById(R.id.restaurant_name))
.getText().toString();
intent.putExtra(TAG_ID, loginId);
intent.putExtra(TAG_NAME, res_name);
startActivity(intent);
}
});
}
});
}
}
}

Android loopj AsyncHttpClient, parsing JSON example

I was looking for a simple example on parsing a JSON file, using the loopj AsyncHttpClient. But so far I could not find any useful information. :(
Simple JSON file to parse:
{
"contact": [
{
"id": "10",
"name": "Tom",
"email": "tom#gmail.com"
}
}
]
}
I would be grateful for any suggestion.
Thanks!!
You need to get the json first. I assume you have done that
{ // json object node
"contact": [ //json array contact
{ // json object node
To parse
JSONObject jb = new JSONObject("your json");
JSONArray con = jb.getJSONArray("contact");
JSONObject contact = (JSONObject) con.getJSONObject(0);
String id = contact.getString("id");
String name = contact.getString("name");
String id = contact.getString("id");
public class MainActivity extends Activity {
private ProgressDialog pdialog;
private static String url = "http://highspecificationservers.com/apk/webservice.php";
private static final String TAG_STUDENT = "student";
private static final String TAG_FNAME = "fname";
private static final String TAG_EMAIL = "email";
private static final String TAG_MOBILE = "mobile";
JSONArray student = null;
ArrayList<HashMap<String, String>> studentlist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
studentlist = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String fname = ((TextView) view.findViewById(R.id.fname))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_FNAME, fname);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_MOBILE, description);
startActivity(in);
}
});
new GetStudent().execute();
}
private class GetStudent extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pdialog = new ProgressDialog(MainActivity.this);
pdialog.setMessage("please wait");
pdialog.setCancelable(false);
pdialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
ServiceHandler sh = new ServiceHandler();
String jString = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response:", "> " + jString);
if (jString != null) {
try {
JSONObject Jsonobj = new JSONObject(jString);
student = Jsonobj.getJSONArray(TAG_STUDENT);
for (int i = 0; i < student.length(); i++) {
JSONObject c = student.getJSONObject(i);
String fname = c.getString(TAG_FNAME);
String email = c.getString(TAG_EMAIL);
String mobile = c.getString(TAG_MOBILE);
HashMap<String, String> student = new HashMap<String, String>();
student.put(TAG_FNAME, fname);
student.put(TAG_EMAIL, email);
student.put(TAG_MOBILE, mobile);
studentlist.add(student);
}
} 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) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (pdialog.isShowing())
pdialog.dismiss();
ListAdapter adapter = new SimpleAdapter(MainActivity.this,
studentlist, R.layout.list_item, new String[] { TAG_FNAME,
TAG_EMAIL, TAG_MOBILE }, new int[] { R.id.fname,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
}
}
private ListView getListView() {
// TODO Auto-generated method stub
return null;
}
}
Go with this...
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_EMAIL, email);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}

Categories

Resources