Hello everyone and happy new year
I have JSON class where I retrieve some data that are retrieve from a database. The format of this JSON file is
{"people":[{"id":"15","first_name":"Theo","last_name":"Tziomakas","bio":"Hello from
Theo!!!","created":"2015-01-11 21:48:51"},
{"id":"16","first_name":"Jim","last_name":"Chytas","bio":"Hello from Chytas","created":"2015-01-11
21:53:42"}]}.
The idea is to retrieve the "first_name" and "second_name" in a listview. The "bio" should appear in another activity,but I don't know how to do that:(.
Here is my code.
public class MainActivity extends ActionBarActivity {
ListView list;
TextView fname;
TextView lname;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://xxxxxxx/tutorials/index.php";
//JSON Node Names
private static final String TAG_OS = "people";
private static final String TAG_FIRST_NAME = "first_name";
private static final String TAG_SECOND_NAME = "last_name";
//private static final String TAG_BIO = "bio";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
new JSONParse().execute();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
fname = (TextView)findViewById(R.id.first_name);
lname = (TextView)findViewById(R.id.last_name);
//abio = (TextView)findViewById(R.id.bio);
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
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String first_name = c.getString(TAG_FIRST_NAME);
String last_name = c.getString(TAG_SECOND_NAME);
//String bio = c.getString(TAG_BIO);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_FIRST_NAME, first_name);
map.put(TAG_SECOND_NAME, last_name);
//map.put(TAG_BIO, bio);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_FIRST_NAME,TAG_SECOND_NAME }, new int[] {
R.id.first_name,R.id.last_name});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String bio = ((TextView) view.findViewById(R.id.bio))
.getText().toString();
switch (position) {
case 0:
Intent i = new Intent(MainActivity.this, SingleActivity.class);
i.putExtra("bio", bio);
startActivity(i);
break;
}
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
And finally I have the SecondActivity class,but nothing is shown when I click the first row of list.
public class SingleActivity extends ActionBarActivity {
TextView text;
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single);
text = (TextView)findViewById(R.id.text);
String bio = getIntent().getStringExtra("bio");
try {
JSONObject profileJSON = new JSONObject(bio);
android = profileJSON.getJSONArray(bio);
text.setText(""+android);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Thank you.
EDIT:The problem I had is fixed. Now I want to do something else. Let us suppose that we update the data in an existing row by changing "first_name,"last_name" and finally bio. It is done very easily in phpmyadmin tool. The problem is that the updated row is not shown in the listview. I have to reinstall the app in order to see it. Any ideas in that?
try this ,
replace onPostExecute with this
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
list=(ListView)findViewById(R.id.list);
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String first_name = c.getString(TAG_FIRST_NAME);
String last_name = c.getString(TAG_SECOND_NAME);
//String bio = c.getString(TAG_BIO);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_FIRST_NAME, first_name);
map.put(TAG_SECOND_NAME, last_name);
map.put(TAG_BIO, bio);
oslist.add(map);
}
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_FIRST_NAME,TAG_SECOND_NAME }, new int[] {
R.id.first_name,R.id.last_name});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String bio =oslist.get(position).get(TAG_BIO);
// switch (position) {
// case 0:
Intent i = new Intent(MainActivity.this, SingleActivity.class);
i.putExtra("bio", bio);
startActivity(i);
break;
//}
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
and SingleActivity
text = (TextView)findViewById(R.id.text);
String bio = getIntent().getStringExtra("bio");
text.setText(bio );
Pay attention to what you put in the intent.
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String bio = ((TextView) view.findViewById(R.id.bio))
.getText().toString();
switch (position) {
case 0:
Intent i = new Intent(MainActivity.this, SingleActivity.class);
i.putExtra("bio", bio);
startActivity(i);
break;
}
}
notice that you take the text from a text view and add it to and intent.
When you retreive it use it as if its a json object.
If you want the bio string, you could put that in a variable, and then send it to an intent with just the string.
for example
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_FIRST_NAME,TAG_SECOND_NAME }, new int[] {
R.id.first_name,R.id.last_name});
list.setAdapter(adapter);
String bio = c.getString("bio");
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position) {
case 0:
Intent i = new Intent(MainActivity.this, SingleActivity.class);
i.putExtra("bio", bio);
startActivity(i);
break;
}
}
});
when retrieving it its easier to just do it with
public class SingleActivity extends ActionBarActivity {
TextView text;
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single);
text = (TextView)findViewById(R.id.text);
String bio = getIntent().getStringExtra("bio");
text.settext(bio)
}
}
now there is prob some bugs in these example, since i have not java or android sdk installed on my computer
Related
How do i pass from a listview when clicked to another listview in the next activity? I retrieved my data in my database, i am trying to filter the selection by their ID and show everything from the same id when i click an item from my listview.
Here is my onclick listview in my first activity
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent (this, Sample.class);
HashMap<String,String> map =(HashMap)parent.getItemAtPosition(position);
String s_id = map.get(Config.TAG_s_id).toString();
String s_name = map.get(Config.TAG_s_name).toString();
String s_gender = map.get(Config.TAG_s_gender).toString();
String teamone = map.get(Config.TAG_teamone).toString();
String teamonepts = map.get(Config.TAG_teamonepts).toString();
String teamtwo = map.get(Config.TAG_teamtwo).toString();
String teamtwopts = map.get(Config.TAG_teamtwopts).toString();
intent.putExtra(Config.S_id,s_id);
intent.putExtra(Config.S_name,s_name);
intent.putExtra(Config.S_gender,s_gender);
intent.putExtra(Config.Teamone,teamone);
intent.putExtra(Config.Teamonepts,teamonepts);
intent.putExtra(Config.Teamtwo,teamtwo);
intent.putExtra(Config.Teamtwopts,teamtwopts);
startActivity(intent);
}
Here is my second activity
editTextId = (EditText) findViewById(R.id.editTextId);
title1ID = (TextView) findViewById(R.id.s_genderID);
contentID = (TextView) findViewById(R.id.s_nameID);
dateID = (TextView) findViewById(R.id.teamone);
teamoneptsID = (TextView) findViewById(R.id.teamonepts);
teamtwoID = (TextView) findViewById(R.id.teamtwo);
teamtwoptsID = (TextView) findViewById(R.id.teamtwopts);
listview = (ListView) findViewById(R.id.listView);
Typeface font = Typeface.createFromAsset(getAssets(), "arial.ttf");
title1ID.setTypeface(font);
contentID.setTypeface(font);
dateID.setTypeface(font);
editTextId.setText(id);
title1ID.setText(titl);
contentID.setText(cont);
dateID.setText(date);
teamoneptsID.setText(teamonepts);
teamtwoID.setText(teamtwo);
teamtwoptsID.setText(teamtwopts);
getResult();
private void getResult() {
class GetResult extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
showResult(s);
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequestParam(Config.URL_Sport1, id);
return s;
}
}
GetResult ge = new GetResult();
ge.execute();
}
private void showResult(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY1);
JSONObject c = result.getJSONObject(0);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showResult(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY2);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String teamone = jo.getString(Config.TAG_teamone);
String teamonepts = jo.getString(Config.TAG_teamonepts);
String teamtwo = jo.getString(Config.TAG_teamtwo);
String teamtwopts = jo.getString(Config.TAG_teamtwopts);
String s_name = jo.getString(Config.TAG_s_name);
String s_gender = jo.getString(Config.TAG_s_gender);
HashMap<String,String> match = new HashMap<>();
match.put(Config.TAG_teamone, teamone);
match.put(Config.TAG_teamonepts,teamonepts);
match.put(Config.TAG_teamtwo,teamtwo);
match.put(Config.TAG_teamtwopts,teamtwopts);
match.put(Config.TAG_s_name,s_name);
match.put(Config.TAG_s_gender,s_gender);
list.add(match);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
Sample.this, list, R.layout.gamesadapterlayout,
new String[]{Config.TAG_teamone,Config.TAG_teamonepts, Config.TAG_teamtwo, Config.TAG_teamtwopts, Config.TAG_s_name, Config.TAG_s_gender},
new int[]{ R.id.team1, R.id.score1, R.id.team2, R.id.score2, R.id.Type, R.id.s_gender});
listview.setAdapter(adapter);
}
I am trying to put everything from my first activity into the next in a listview by taking all of the same id with the clicked item. What im getting instead is a textview of the same id with only 1 result and not in a listview.
Can someone help me please.
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.
I'm really new to android programming, I successfully get data from server and then populated into a listview. But how do I auto-refresh the listview items within certain amount of time? There maybe new items coming in from the server when I refresh the new items may appear.
Here's my code of retrieving data from server:
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
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;
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);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)getView().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> {
public ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
number = (TextView)getView().findViewById(R.id.number);
info = (TextView)getView().findViewById(R.id.info);
remark = (TextView)getView().findViewById(R.id.remark);
statuss = (TextView)getView().findViewById(R.id.statuss);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
public JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
public 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)getView().findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,
R.layout.list_view,
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(getActivity(), "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
String numberr = oslist.get(position).get("phonenumber");
Intent intent = new Intent(getActivity(), ThreeButton.class);
intent.putExtra("key", numberr);
startActivity(intent);
}
}
);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
i would recommend you to use handler for refreshing data. i.e
final Handler handler = new Handler();
Runnable refresh = new Runnable() {
#Override
public void run() {
new JSONParse().execute();
handler.postDelayed(this, 60 * 1000);
}
};
handler.postDelayed(refresh, 60 * 1000);
this handler refresh data for every minute.
To prevent the adding the same data in list view you should use following things :
Please paste following code inside the onPost() method of the AsyncTask before for loop :
if(oslist!=null && oslist.size()>0)
oslist.clear();
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;
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);
}
});
}
});
}
}
}