Binding data through PHP to Android using JSON - java

I am developing an android application using PHP and mysql as external database. Now in my activity page whole JSON data are there but not bind in listview. I tried a lot and search on google as well.
My activity.java is below:
private void getdatalatlog(double latitude, double longitude) {
String link = "http://192.168.0.104/PHP/webservice/comments.php?latitude='"+latitude+"'&longitude='"+longitude+"'";
aq.progress(R.id.progressBar1).ajax(link, JSONObject.class, this,"jsonCallback");
}
public void jsonCallback(String link, JSONObject json, AjaxStatus status) throws JSONException {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
json = jParser.getJSONFromUrl(link);
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);
}
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.single_post, new String[] { TAG_TITLE,TAG_USERNAME ,TAG_MESSAGE
}, new int[] { R.id.shop_name,R.id.address,R.id.distance
});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
My getdatalatlong() method is called in onCreate() method. And in jsonCallback() method's json object, I got all data of my database.

Check whether you are getting the JSON Object from the server.
if you got means do this. Store that JSON Result in an string(usually i call it JSONString).
For example :
{
"username":"Vignesh";
"title" : "Check My Site";
"content" : "vickytechy.hol.es"
}
Then use this to get the values by the index
JSONObject jsonObject = new JSONObject(JSONString);//JSONString is the JSON result;
Name = jsonObject.optString("username");//Name = Vignesh
Title = jsonObject.optString("title");//Title = Check My Site
Content = jsonObject.optString("content");//Content = vickytechy.hol.es

Related

How to send array of Hashmap from one activity to another activity in android

I have a list view in Main activity, I have fill some values in it by using Array Adapter
String[] arr = new String[]{"Android ListView Item 1", "Android ListView Item 2",
"Simple List View In Android", "List View onClick Event","Android List View OnItemClickListener",
"Open New Activity When ListView item Clicked", "List View onClick Source Code", "List View Array Adapter Item Click",
};
Now I want to set onclickListener to each item of the list. I am requesting an api which gives me jsonresponse and I want to iterate over jsonresponse and send required data to another activity when click item of the list.
I tried with following:
ArrayAdapter<String> arrayadapter = new ArrayAdapter<String>(this,
R.layout.activity_main2, R.id.textview, arr);
listview.setAdapter(arrayadapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String textToPass = "hello";
if (position == 0) {
Bundle passData = new Bundle();
passData.putString("data",textToPass);
Intent myIntent = new Intent(view.getContext(), Main2Activity.class);
myIntent.putExtras(passData);
startActivity(myIntent);
}
}
});
}
private String jsonParse(){
String url = "//testing/api.php"; //get json response locally
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray jsonArray = null;
try {
jsonArray = response.getJSONArray("Item");
for(int i=0; i<=jsonArray.length();i++){
HashMap<String,String> dict = new HashMap<String,String>();
JSONObject tv = jsonArray.getJSONObject(i);
String sid;
dict.put("cid", tv.getString("sid") );
// String cid = tv.getString("sid");
String categoryName =tv.getString("category_name");
String baseUrl = "//testing/";
String imageUrl = baseUrl + tv.getString("category_image");
//textView.append(cid + "," + categoryName + "," + imageUrl + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
assert jsonArray != null;
Log.d("Main",jsonArray.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(error.getMessage(), "utf-8");
}
});
requestQueue.add(jsonObjectRequest);
Please help
If I understood properly then I think you want to send HashMap dic to another activity. HashMap are serializable this means you can easily pass it in intent, moreover both key and value are string which are also serializable
intent.putExtra("dic.key", dic);
And in your next activity retrieve it with typecasting.. simple
HashMap<String, String> hashMap = (HashMap<String, String>) intent.getSerializableExtra("hashMap");

how to get listview data from parseJson

hi please answer my question
i have this code in eclipse for Android Developing.
i am using mysql and php for database and get data with JSON . But i dont know how can i use JSONparse data in listview . please edit my codes.
public class ViewAllPersons extends Activity {
String url = "http://192.168.1.206/androhp/view_all_persons.php";
ArrayList<String> result;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_all_person);
result = new ArrayList<String>();
LoadAllPersons lap = new LoadAllPersons();
lap.execute(url);
}
class LoadAllPersons extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
InputStream jsonStream = getStreamFromURL(args[0], "GET");
String jsonString = streamToString(jsonStream);
parseJSON(jsonString);
return null;
}
void parseJSON(String JSONString) {
try {
JSONObject jo = new JSONObject(JSONString);
JSONArray allpersons = jo.getJSONArray("allpersons");
for (int i = 0; i < allpersons.length(); i++) {
JSONObject object = allpersons.getJSONObject(i);
String objString = "";
objString = object.getString("name") + " , "
+ object.getString("name2") + " : "
+ object.getInt("iconlink");
result.add(objString);
}
} catch (JSONException e) {
}
}
protected void onPostExecute(String file_url) {
list = (ListView) findViewById(R.id.list);
String[] web = {
"Google Plus",
"Twitter",
"Windows"
} ;
String[] imageUrl = {
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png",
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png",
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png"
};
CustomList adapter = new
CustomList(ViewAllPersons.this, web, imageUrl);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
How can I use parseJSON data instead of web listview :
list = (ListView) findViewById(R.id.list);
String[] web = {
"Google Plus",
"Twitter",
"Windows"
} ;
String[] imageUrl = {
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png",
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png",
"http://www.varzesh3.com/football3_Images/varzesh3-logo.png"
};
You have got both data as well as list, now you need to combine them.
first you have to convert your json result into list, where values are your json values.
final ArrayList<String> listdata = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
listdata .add(values[i]);
}
then you have to assign adapter to your list. You can use following code.
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.yourlistlayout, listdata );
list.setAdapter(adapter);
More details
http://www.vogella.com/tutorials/AndroidListView/article.html

Android parsing Json error

I having an error while parsing json array in my android application.
My json object is in the following form:
{"post":[
[{"0":"all the best to every one...!!","post":"all the best to every one...!!"},
{"0":"hello every one...","post":"hello every one..."}]
]}
My java file in android is as follows:
public class Newsactivity extends ListActivity {
private static final String TAG_SUCCESS = "";
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> postsList;
private static String url_all_products = "myurl";
private static final String TAG_POST = "post";
JSONArray posts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.allposts);
postsList = new ArrayList<HashMap<String, String>>();
new LoadAllProducts().execute();
ListView lv = getListView();
}
class LoadAllProducts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Newsactivity.this);
pDialog.setMessage("Loading posts. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
Log.d("All Posts: ", json.toString());
try {
posts = json.getJSONArray(TAG_POST);
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
String post = c.getString(TAG_POST);
HashMap<String,String> map = new HashMap<String,String>();
map.put(TAG_POST, post);
postsList.add(map);
}
} 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(
Newsactivity.this, postsList,
R.layout.singlepost, new String[] { TAG_POST},
new int[] { R.id.pid});
setListAdapter(adapter);
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_newsactivity, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I am getting a fatal exception starting this activity. This code is modified code of an online tutorial on json parsing. As I am new to android I am unable to find where the id is. So, please help me. Thank you.
I am afraid that your json format is "a little bit strange" (or i may say it is in a different format with what your code is trying to do) according to your code.
As you can see, there are two "[" after the first "post", which means the array of elements is actually inside another array.
{"post":[ // first '['
[ // second '['
{"0":"all the best to every one...!!","post":"all the best to every one...!!"},
{"0":"hello every one...","post":"hello every one..."}
]
]}
so to make it correct, do following
try {
posts = json.getJSONArray(TAG_POST);
posts = posts.getJSONArray(0) // to get the first array
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
String post = c.getString(TAG_POST);
HashMap<String,String> map = new HashMap<String,String>();
map.put(TAG_POST, post);
postsList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
as your json responce having nested array you need to code like this...
JSONObject json; = jParser.makeHttpRequest(url_all_products, "GET", params);
Log.d("All Posts: ", json.toString());
try {
posts = json.getJSONArray(TAG_POST);
for (int i = 0; i < posts.length(); i++) {
subposts = posts.getJSONArray(i);
for (int j = 0; j < subposts.length(); j++) {
JSONObject c = subposts.getJSONObject(i);
String post = c.getString(TAG_POST);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_POST, post);
postsList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this:
posts = json.getJSONArray(TAG_POST);
for (int i = 0; i < posts.getJSONArray(0).length(); i++) {
JSONObject c = posts.getJSONArray(0).getJSONObject(i);
String post = c.getString("0");
HashMap<String,String> map = new HashMap<String,String>();
map.put(TAG_POST, post);
postsList.add(map);
}

JSON respone in list view display based on the particular condition in android

I need to display the items on particular condition .I done that one.I have three tabs are present.In the first tab A ,i display the list of items,in that only one item is present.But when you move to tab B and again come to tab A,we can see two items.I need to avoid that repeating item displaying, how to do that one, please help me if you have an idea,Thank you in advance
Here is my code:
List View list;
ListViewAdapter adapter;
ArrayList<String> title_array = new ArrayList<String>();
ArrayList<String> title_array1 = new ArrayList<String>();
ArrayList<String> title_array2 = new ArrayList<String>();
ArrayList<String> title_array3 = new ArrayList<String>();
ArrayList<String> title_array4 = new ArrayList<String>();
ArrayList<String> title_array5 = new ArrayList<String>();
ArrayList<String> title_array6 = new ArrayList<String>();
String response_value;
JSONObject result;
JSONArray tokenList;
JSONObject oj5;
String appid;
JSONObject oj;
String fileid;
HttpEntity entity;
String status ,borrowername,coborrowername,loannumber,addrs1,city;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.menu_frame, container, false);
list = (ListView) rootView.findViewById(R.id.listview);
// Pass results to ListViewAdapter Class
new AsyncTaskParseJson().execute();
return rootView;
}
// you can make this class as another java file so it will be separated from your main activity.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
// post the specific format data to json url
try {
HttpClient httpClient = new DefaultHttpClient();
JSONObject object = new JSONObject();
object.put("Username", "******");
object.put("Password", "******");
JSONObject jsonObject = new JSONObject();
jsonObject.put("Authentication", object);
jsonObject.put("RequestType", 4);
HttpPost postMethod = new HttpPost("*********");
postMethod.setEntity(new StringEntity(jsonObject.toString()));
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(postMethod);
entity = response.getEntity();
response_value = EntityUtils.toString(entity).toString();
// Log.e(TAG, response_value);
if (entity != null) {
//Convert String to JSON Object
JSONObject result = new JSONObject(response_value);
JSONArray tokenList = result.getJSONArray("Files");
}
} catch (Exception e) {
e.printStackTrace();
}
return response_value;
}
#Override
protected void onPostExecute(String response_value) {
super.onPostExecute(response_value);
// dismiss the dialog after getting all products
try
{
if (entity != null) {
result = new JSONObject(response_value);
tokenList = result.getJSONArray("Files");
for(int i=0;i<=tokenList.length();i++)
{
oj = tokenList.getJSONObject(i);
String oj1 = oj.getString("FileID");
JSONObject oj12= (JSONObject) tokenList.getJSONObject(i).get("Borrower");
JSONObject oj2 = (JSONObject) tokenList.getJSONObject(i).get("CoBorrower");
JSONObject oj3 = (JSONObject) tokenList.getJSONObject(i).get("LoanDetails");
JSONObject oj4 = (JSONObject) tokenList.getJSONObject(i).get("PropertyAddress");
fileid = oj.getString("FileID");
borrowername = oj12.getString("FirstName");
coborrowername = oj2.getString("FirstName");
loannumber = oj3.getString("LoanNumber");
addrs1 = oj4.getString("Address1");
city = oj4.getString("City");
JSONArray orders = oj.getJSONArray("Orders");
for(int n=0;n<orders.length();n++){
JSONObject oj5 = orders.getJSONObject(n);
appid = oj5.getString("ApplicationOrderId");
String duedate = oj5.getString("DueDate");
status = oj5.getString("Status");
// Log.e(TAG, appid +"/"+ appid1);
Log.e(TAG, appid + "/" + borrowername + "/"+ coborrowername + "/"+ addrs1 + "/"+ city + "/"+ loannumber + fileid );
if(status.equals("1")){
title_array3.add("New");
title_array1.add(addrs1 + " ,"+ city);
title_array.add(borrowername +" , "+coborrowername);
title_array2.add("Duedate");
// title_array3.add(status);
title_array4.add(appid);
title_array5.add(loannumber);
title_array6.add(fileid);
list.setOnItemClickListener(new OnItemClickListener() {
#Override public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
Intent first = new Intent(getActivity(),DetailView.class);
first.putExtra("fileid", fileid);
startActivity(first);
} });
}
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
adapter = new ListViewAdapter(getActivity(), title_array,title_array1,title_array2,title_array3,title_array4,title_array5,title_array6);
list.setAdapter(adapter);
}
}
}

Android listview adapter in listview (json children)

Sorry.... I'm new in android....
I have done such schema:
i created listview in my activity, and put on it adapter with own activity as in all tutorials...
But now i must to go further and create more complicated activity: on every my listview adapter view i must put another loop with data => other listview with adapter... Is it real?
Here is my code(i do it in education goal):
protected void onCreate(Bundle savedInstanceState) {
String bank;
bank = this.getIntent().getStringExtra("Bank_id");
url = "http://192.168.1.4:3000/exchanger_lists/get_bank_exchanger_list/"+bank+".json";
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bank_exchangers_list);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
banks = json.getJSONArray(TAG_Exchangers);
// looping through All Contacts
for(int i = 0; i < banks.length(); i++){
JSONObject c = banks.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_address);
String location_name = c.getString(TAG_location_name);
String latitude = c.getString(TAG_latitude);
String longitude = c.getString(TAG_longitude);
String exchanger_type_name = c.getString(TAG_exchanger_type_name);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_address, address);
map.put(TAG_location_name, location_name);
map.put(TAG_latitude, latitude);
map.put(TAG_longitude, longitude);
map.put(TAG_exchanger_type_name, exchanger_type_name);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.bank_exchanger_list_element,
new String[] { TAG_NAME, TAG_location_name, TAG_address, TAG_exchanger_type_name, TAG_latitude, TAG_longitude }, new int[] {
R.id.bank_e_n, R.id.nas_punkt_e_n , R.id.adress_obm_e_n , R.id.tip_obm_e_n , R.id.shirota_e_n , R.id.dolgota_e_n });
setListAdapter(adapter);
}
i need to parse json children for each TAG_Exchangers and add in as an adapter for adapter listAdapter adapter = new SimpleAdapter(this, contactList, .......
Is it real? And how to do it?
why not using BaseAdapter , where you rule everything related to how it looks and how it uses the data? just implement getCount,getItem, and getView .
for more information about listView, watch "the world of listView" lecture.

Categories

Resources