App crashed when JSONObject get called - android

I wanted to retrieve the data from MySQL to android listView. I have follow each single steps from this tutorial, however it crashed when I trying to call JSON object. Please help. Thanks a lot..
private ListView listView;
String myJSON;
JSONArray information = null;
ArrayList<HashMap<String, String>> infoList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
infoList = new ArrayList<HashMap<String, String>>();
listView = (ListView) findViewById(R.id.listView2);
getData();
}
public void getData() {
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://192.168.107.115:80/Android/CRUD/retrieveInformation.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
information = jsonObj.getJSONArray(Config.TAG_RESULTS);
for(int i=0;i<information.length();i++){
JSONObject c = information.getJSONObject(i);
String date = c.getString(Config.TAG_DATE);
Toast.makeText(getApplicationContext(),date,Toast.LENGTH_LONG).show();
String timeIn = c.getString(Config.TAG_TiME_IN);
Toast.makeText(getApplicationContext(),timeIn,Toast.LENGTH_LONG).show();
String timeOut = c.getString(Config.TAG_TIME_OUT);
HashMap<String,String> info = new HashMap<String,String>();
info.put(Config.TAG_DATE, date);
info.put(Config.TAG_TiME_IN, timeIn);
info.put(Config.TAG_TIME_OUT,timeOut);
infoList.add(info);
}
ListAdapter adapter = new SimpleAdapter(
HomePage.this, infoList, R.layout.retrieve_data,
new String[]{Config.TAG_DATE,Config.TAG_TiME_IN,Config.TAG_TIME_OUT},
new int[]{R.id.date,R.id.timeIn,R.id.timeOut}
);
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
retrieveInformation.php
<?php
define('HOST','127.0.0.1:3307');
define('USER','root');
define('PASS','');
define('DB','androiddb');
$con = mysqli_connect(HOST,USER,PASS,DB) or die('unable to connect');
$sql = "select * from information";
$res = mysqli_query($con,$sql);
$result=array();
while($row=mysqli_fetch_array($res)){
array_push($result,array('id'=>$row[0],'name'=>$row[1],'weather'=>$row[2],'date'=>$row[3],'status'=>$row[4],
'time_in'=>$row[5], 'time_out'=>$row[6]));
}
print(json_encode(array("result"=>$result)));
mysqli_close($con);
?>
LogCat
Process: com.example.project.myapplication, PID: 31622
java.lang.NullPointerException
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:155)
at org.json.JSONObject.<init>(JSONObject.java:172)
at com.example.project.myapplication.GUI.HomePage.showList(HomePage.java:185)
at com.example.project.myapplication.GUI.HomePage$1GetDataJSON.onPostExecute(HomePage.java:176)
at com.example.project.myapplication.GUI.HomePage$1GetDataJSON.onPostExecute(HomePage.java:137)
at android.os.AsyncTask.finish(AsyncTask.java:632)
Code
`JSONObject jsonObj = new JSONObject(myJSON);` ,
class GetDataJSON extends AsyncTask<String, Void, String> {
and showList();.

Make a stupid mistake again. forget to switch on the wifi-connection

Related

Android Development - Parsing JSON

I'm trying to get the values from my mySql database and display them in a listView. However when I click the button to display them I get the following error message : org.json.JSONException: No value for establishments.
I know that the TAG_RESULTS is empty but I don't know what I'm supposed to put in to it.
Here is my code
public class SecondPage extends AppCompatActivity {
String myJSON;
//There is no value for this TAG_RESULTS ON LINE 116
private static final String TAG_RESULTS="establishments";
private static final String TAG_NAME = "name";
private static final String TAG_PICTURE = "picture";
JSONArray establishments_JSON = null;
ArrayList<HashMap<String, String>> establishmentsList;
//JSONArray establishments = null;
//Array establishments = null;
ListView listView ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.current_location_listview);
listView = (ListView) findViewById(R.id.listView);
establishmentsList = new ArrayList<HashMap<String,String>>();
getData();
}
public void getData(){
//changed the middle parameter to a string from a void
class GetDataJSON extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
Log.d("GETTING JSON DATA", "HERE....");
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://10.102.11.109/findandeat_xampp_data/get_all_establishments.php");
//String loginDetails = ServerConnection.RUSH_SERVER_ADDRESS + "login.php?userName=" + userNameInput + "&password=" + passwordInput;
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
Log.d("STARTING INPUT STREAM", "HERE....");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
result = sb.toString();
} catch (Exception e) {
// Oops
Log.d("CATCH ANY ERRORS", "HERE....");
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
Log.d("myjson",myJSON);
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void showList(){
try {
Log.d("myjson",myJSON);
JSONObject jsonObj = new JSONObject(myJSON);
establishments_JSON = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<establishments_JSON.length();i++){
JSONObject c = establishments_JSON.getJSONObject(i);
String pizzeriaName = c.getString(TAG_NAME);
String pizzeriaPicture = c.getString(TAG_PICTURE);
String chineseName = c.getString(TAG_NAME);
String chinesePicture = c.getString(TAG_PICTURE);
String cafeName = c.getString(TAG_NAME);
String cafePicture = c.getString(TAG_PICTURE);
String indianName = c.getString(TAG_NAME);
String indianPicture = c.getString(TAG_PICTURE);
String ChipShopName = c.getString(TAG_NAME);
String ChipShopPicture = c.getString(TAG_PICTURE);
//Error im getting is that there is no value for the result
//with the JSON
HashMap<String,String> establishment_items = new HashMap<String,String>();
establishment_items.put(TAG_NAME,pizzeriaName);
establishment_items.put(TAG_PICTURE,pizzeriaPicture);
establishment_items.put(TAG_NAME,chineseName);
establishment_items.put(TAG_PICTURE,chinesePicture);
establishment_items.put(TAG_NAME,cafeName);
establishment_items.put(TAG_PICTURE,cafePicture);
establishment_items.put(TAG_NAME,indianName);
establishment_items.put(TAG_PICTURE,indianPicture);
establishment_items.put(TAG_NAME,ChipShopName);
establishment_items.put(TAG_PICTURE,ChipShopPicture);
establishmentsList.add(establishment_items);
}
ListAdapter adapter = new SimpleAdapter(
SecondPage.this, establishmentsList, R.layout.activity_current_location_items,
new String[]{TAG_NAME,TAG_PICTURE},
new int[]{R.id.establishment_name, R.id.establishment_picture}
);
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
XMLdatabase column names
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView" />
column name in database
The other types of restuarants have the same naming system applied
It will generate this error because there is the parameter you want. So you can validate:
//if exists
if(jsonObj.has(TAG_RESULTS)){
}
The same should do to verify certain parameters exist or not in the JSON object, so you save trouble with exceptions.
use .has(String) and isNull(String)
.has(String) checks if the JSONObject contains a specific key
.isNull(String) checks if the value associated with the key is null or if there is no value
So , your code will be
if (jsonObj.has(TAG_RESULTS) && !jsonObj.isNull(TAG_RESULTS)) {
establishments_JSON = jsonObj.getJSONArray(TAG_RESULTS);
}
I hope to be helpful for you .

Android - retrieving json via HTTPS

I've a problem with parsing json from facebook graph api.
When I'm using facebook URL:https://graph.facebook.com/interstacjapl/feed?access_token=MyTOKEN to grab json it's no working, but when I copied that json (it works in browser) and paste to my webiste http://mywebsite/fb.json and change site URL in the code, it works good.
When I'm using fb graph URL it shows error:
W/System.err(5534): org.json.JSONException: No value for data
Is this problem with parsing from https or URL or code?
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
MainActivity
public class MainActivity extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "https://graph.facebook.com/interstacjapl/feed?access_token=CAACEdEose0cBANLR...";
//JSON Node Names
private static final String TAG = "data";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "message";
private static final String TAG_API = "type";
JSONArray android = 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();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
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);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_ID,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
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();
}
}
}
}
This works
String reply = "";
BufferedReader inStream = null;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(httpRequest);
inStream = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()));
StringBuffer buffer = new StringBuffer("");
String line = "";
while ((line = inStream.readLine()) != null) {
buffer.append(line);
}
inStream.close();
reply = buffer.toString();
} catch (Exception e) {
//Handle Execptions
}

How to put data in listview which received using AsyncTask?

I am successfully retrieving but unable to put data into listview. how to update ui thread
after retrieving data.
here is the class of asynctask that retrieves data
I tried to update in onPostExecute but couldn't succeed.
class GetJson extends AsyncTask<String, Integer, ArrayList<RowItem>> {
ArrayList<RowItem> rowItems = new ArrayList<RowItem>();
//ArrayList<ArrayList<String>> fullscreens = new ArrayList<ArrayList<String>>() ;
public AsyncResponse delegate = null;
private CustomListViewAdapter arrayadapter;
private ProgressDialog pDialog;
private Context Mycontext;
private ArrayList<String> alist;
private ListView listView;
public GetJson(Context cnxt,ArrayList<String> alist, CustomListViewAdapter adapt,ListView listView) {
Mycontext = cnxt ;
//this.rowItems = rowItems;
this.alist = alist;
this.listView = listView;
}
#Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
this.pDialog = new ProgressDialog(Mycontext);
this.pDialog.setMessage("Please wait..");
this.pDialog.setIndeterminate(true);
this.pDialog.setCancelable(false);
this.pDialog.show();
//alist.add("fifa");
}
#Override
protected ArrayList<RowItem> doInBackground(String... passing) {
here i am recieving data
return rowItems;
}
#Override
protected void onPostExecute(ArrayList<RowItem> Items) {
super.onPostExecute(Items);
this.pDialog.dismiss();
}
}
I laso tried runuithread in doinBackgroung method
there also i am getting runtime errors
here is my code
protected Void doInBackground(Void... unused) {
runOnUiThread(new Runnable() {
public void run() {
String result = null;
InputStream is = null;
JSONObject json_data=null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
JSONArray ja = new JSONArray();
List<NameValuePair> params = new LinkedList<NameValuePair>();
for(String s : alist)
{
Log.d("s",s);
params.add(new BasicNameValuePair("list[]",s));
}
try{
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
// 2. make POST request to the given URL
HttpGet httpPost = new HttpGet("http://10.0.3.2/infogamma/getapps.php?"+paramString);
// 4. convert JSONObject to JSON to String
String json = ja.toString();
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
//String json = EntityUtils.toString();
is = entity.getContent();
// Log.d("response", ");
}
catch(Exception e){
Log.i("taghttppost",""+e.toString());
}
//parse response
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuilder stringbuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
stringbuilder.append(line + "\n");
}
is.close();
result = stringbuilder.toString();
Log.d("ans",result);
}
catch(Exception e)
{
Log.i("tagconvertstr",""+e.toString());
}
//get json data
try{
//JSONObject json = new JSONObject(result);
JSONArray jArray = new JSONArray(result);
Log.d("app_lentgh", Integer.toString(jArray.length()));
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
// this.donnees.add("title: "+ json_data.getString("title") + " appid: " + json_data.getString("appid") );
try{
//commmand http
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://10.0.3.2/infogamma/getAppDetails.php?appid="+json_data.getString("appid"));
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
//String json = EntityUtils.toString();
is = entity.getContent();
// Log.d("response", ");
}
catch(Exception e){
Log.i("taghttppost",""+e.toString());
}
//parse response
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.d("ans",result);
}
catch(Exception e)
{
Log.i("tagconvertstr",""+e.toString());
}
ArrayList<String> screenitem = new ArrayList<String>();
try{
JSONObject j = new JSONObject(result);
screenitem.add(j.getString("scr1"));
screenitem.add(j.getString("scr2"));
screenitem.add(j.getString("scr3"));
// this.fullscreens.add(screenitem);
// RowItem(ImageView imageId, String title, String desc,String catgs,String downloads,String rating,String discription)
RowItem item = new RowItem(j.getString("coverimage"), j.getString("title"), j.getString("category"),j.getString("downloads"),j.getString("rating"),
j.getString("scr1"),j.getString("scr2"),j.getString("scr3"),j.getString("discription"),j.getString("developer"),j.getString("price")
,json_data.getString("appid"));
rowItems.add(item);
}
catch(JSONException e){
Log.i("tagjsonexp",""+e.toString());
}
//SharedPreferences.Editor editor = ((Activity) Mycontext).getPreferences(Mycontext.MODE_PRIVATE).edit();
//editor.;
//editor.commit();
//Log.i("title",json_data.getString("title"));
}
}
catch(JSONException e){
Log.i("tagjsonexp",""+e.toString());
} catch (ParseException e) {
Log.i("tagjsonpars",""+e.toString());
}
adapt = new CustomListViewAdapter(getApplicationContext(),
R.layout.list_item, rowItems);
listView.setAdapter(adapt);
}});
return (null);
}
You can populate the list view from doInBackground by this code
runOnUiThread(new Runnable() {
public void run() {
//set listview Adapter here
}
});
this thing is not preferable. One more thing you can do is create a class which can hold the data you want to show on the item of a list and pass the array of that class object to onPostExecute method from where you can handle the UI thread.
Do it in onPostExecute() or if you want to add them from doInBackground() instantly, do it using runOnUiThread().
Edit:
After reading your comments, You are using CustomListViewAdapter, do you have a constructor with Context,int,ArrayList<String> as parameters in your adapter class?

Android sent to php (httppost) "Undefined index: txtProvinceId "Help Me please

public class DialogSelectAmphurActivity extends Activity {
private final String TAG = "internet";
private ListView listview_province;
ArrayList<HashMap<String, String>> myList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
String strUrl =("http://192.168.1.4/test_projectEnd/amphur.php");
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_select_province_dialog);
new AsyncDownload().execute(strUrl);
}
public String getData(String strUrl, ArrayList<NameValuePair> params){
String jString;
HashMap<String, String> map;
String sProvince_id = getIntent().getStringExtra("provinceId");
params.add(new BasicNameValuePair("txtProvinceId",sProvince_id));
try {
jString = getJsonFromUrl(strUrl, params);
JSONArray jArray = new JSONArray(jString);
Log.d(TAG, jArray +","+ params);
for(int i =0; i< jArray.length(); i++)
{
JSONObject jObj = jArray.getJSONObject(i);
String sAmphur_id = jObj.getString("AMPHUR_ID");
String sAmphur_name = jObj.getString("AMPHUR_NAME");
map = new HashMap<String, String>();
map.put("amphur_id", sAmphur_id);
map.put("amphur_name", sAmphur_name);
myList.add(map);
Log.d(TAG, sAmphur_id + sAmphur_name);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private void showProvince(){
ListView listView = (ListView) findViewById(R.id.listView_province1);
ListAdapter adapter = new SimpleAdapter(this, myList, R.layout.row_layout_select_province,
new String[]{"amphur_id","amphur_name"}, new int[]{R.id.textView_province_id,R.id.textView_province_name});
listView.setAdapter(adapter);
}
private String getJsonFromUrl(String strUrl,ArrayList<NameValuePair> params)throws IOException{
URL url = new URL(strUrl);
HttpPost httpPost = new HttpPost(strUrl);
try {
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
Log.d(TAG, params+"check");
httpCon.setRequestMethod("GET");
httpCon.setConnectTimeout(6*1000);
int responseCode = httpCon.getResponseCode();
Log.d(TAG, "The response is" + responseCode);
if(responseCode == HttpsURLConnection.HTTP_OK){
Log.d(TAG, "size" + httpCon.getContentLength());
InputStream ins = httpCon.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(ins,"UTF-8"));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null){
response.append(line);
response.append("\n");
Log.d(TAG, line);
}
rd.close();
return response.toString();
}
} catch (Exception ex) {
Log.d(TAG,"Problem reading"+ ex.getLocalizedMessage());
}
return null;
}
private class AsyncDownload extends AsyncTask<String, Void, String>{
ProgressDialog pd;
#Override
protected void onPreExecute(){
pd = ProgressDialog.show(DialogSelectAmphurActivity.this, "Download", "Downloading....");
}
protected String doInBackground(String... Params){
String data = getData(strUrl, params);
return null;
}
protected void onPostExecute(String result){
pd.dismiss();
showProvince();
}
}
}
i sent txtprovinceId to php
"Sorry for any incorrect on my conversation, my English is not good."
<?php
$provinceid = trim($_GET["txtProvinceId"]);
require("libs/connection_to_abc.php");
mysql_query("SET character_set_results=utf8");
mysql_query("SET character_set_client=utf8");
mysql_query("SET character_set_connection=utf8");
$strSQL = "SELECT amphur.* FROM province,amphur
WHERE province.PROVINCE_ID = amphur.PROVINCE_ID
AND province.PROVINCE_ID ='$provinceid' ";
$objQuery = mysql_query($strSQL);
$intNumField = mysql_num_fields($objQuery);
$resultArray = array();
while($obResult = mysql_fetch_array($objQuery))
{
$arrCol = array();
for($i=0;$i<$intNumField;$i++)
{
$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
}
array_push($resultArray,$arrCol);
}
mysql_close($link);
echo json_encode($resultArray);
?>
php response in Logcat "Undefined index: txtProvinceId in amphur.php on line 3"
Help me please ! "Sorry for any incorrect on my conversation, my English is not good."
You never add your params to the query string. You can use URLEncodedUtils.format() to format them easily :
import org.apache.http.client.utils.URLEncodedUtils;
...
private String getJsonFromUrl(String strUrl,ArrayList<NameValuePair> params) {
String queryString = URLEncodedUtils.format(params, null);
URL url = new URL(strUrl + "?" + queryString);
...
}

async task issue in json format

i have a problem while im get the data from the server in text i can't converted into json object can not be converted into json array i just get the title and author from the database and show in list view
{"document":[{"id":"1","title":"complete refrence of android",
"author":"parag vyas","description":"lnvkzxhbkgbovdghognsdkhogjhlldnglj"}]}
plz help me
public class showalbooks extends Activity {
ArrayList<String> mylist = new ArrayList<String>();
String returnString="";
ListView listView ;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showalbooks);
listView = (ListView) findViewById(R.id.mylist);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://192.168.1.156/recess/document/document.json");
HttpClient client = new DefaultHttpClient();
HttpResponse response=null;
try{
response = client.execute(httpGet);
}
catch(Exception e){}
System.out.println(response.getStatusLine());
String text = null;
try {
response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
String var =text;
try{
JSONArray jArray = new JSONArray(var);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getString("id")+
", title: "+json_data.getString("title")
);
returnString += "\n" +"id:"+ json_data.getString("id")+" "+"Title:"+ json_data.getString("title");
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
listView.setFilterText(returnString);
return returnString;
}
protected void onPostExecute(String results) {
if (results!=null) {
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View listview,
int documentid, long documenttitle) {
// TODO Auto-generated method stub
}
});
}
}}}
The JSON array is enclosed by a JSON object, and has the id "document".
instead of:
JSONArray jArray = new JSONArray(var);
You should have:
JSONObject jObj = new JSONObject(var);
JSONArray jArray = jObj.getJSONArray("document");

Categories

Resources