Displaying database records in android using JAVA RESTful webservice - java

I am trying to display database record using java restful web service. I have able to create a login form using it but I cannot display the records on the database. I tried this code but its not working at all. When button is pressed nothing happens. Heres my code.
DriverDetails.java
class Details extends Activity {
TextView name1;
TextView plate1;
Button Btngetdata;
//URL to get JSON Array
private static String url = "http://192.168.254.108:8080/taxisafe/display/taxidetails";
//JSON Node Names
private static final String TAG_USER = "taxi";
private static final String TAG_NAME = "taxi_name";
private static final String TAG_EMAIL = "taxi_plate_no";
JSONArray user = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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> {
#Override
protected void onPreExecute() {
super.onPreExecute();
name1 = (TextView)findViewById(R.id.name);
plate1 = (TextView)findViewById(R.id.plate);
}
#Override
protected JSONObject doInBackground(String... args) {
HttpConnection jParser = new HttpConnection();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
// Getting JSON Array
user = json.getJSONArray(TAG_USER);
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a Variable
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
//Set JSON Data in TextView
name1.setText(name);
plate1.setText(email);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
HttpConnection.java
public class HttpConnection {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public HttpConnection() {
}
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;
}
}

I suggest adding Volley to your project
https://developer.android.com/training/volley/index.html
and following the example here https://developer.android.com/training/volley/request.html#request-json
You will not need to create your own HTTP request. Let Volley handle the network request using JSONObjectRequest

Related

Can't get the value from doInBackGround() process at onPostExecute()

I'm using AsyncTask to insert, update and delete data from database. I used this code to insert, update, delete and it works fine. But when I want to use select, and show the data at EditText, I can't get the value from doInBackground() to the onPostExecute() and it shows nothing.
Here's my code :
MenuUtama.java
public class MenuUtama extends Activity {
/** Called when the activity is first created. */
private TextView nama_user;
private String nm_user = "";
private EditText kode, nama, harga, deskripsi;
private Button insert, update, delete, cek;
private String kode1, nama1, harga1, deskripsi1;
JSONArray data = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
kode = (EditText) findViewById(R.id.editKode);
nama = (EditText) findViewById(R.id.editNama);
harga = (EditText) findViewById(R.id.editHarga);
deskripsi = (EditText) findViewById(R.id.editDes);
cek = (Button) findViewById(R.id.btnCek);
insert = (Button) findViewById(R.id.buttonInsert);
update = (Button) findViewById(R.id.buttonUpdate);
delete = (Button) findViewById(R.id.buttonDelete);
nama_user = (TextView) findViewById(R.id.textView3);
Intent i = getIntent();
nm_user = i.getStringExtra("nama_user");
nama_user.setText(nm_user);
insert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "";
url = "http://192.168.1.10/crudsederhana/aksi.php";
try {
String ko = URLEncoder.encode(kode.getText().toString(),"utf-8");
String n = URLEncoder.encode(nama.getText().toString(),"utf-8");
String hr = URLEncoder.encode(harga.getText().toString(),"utf-8");
String d = URLEncoder.encode(deskripsi.getText().toString(), "utf-8");
url += "?a=insert&kd=" + ko + "&nm=" + n + "&hrg=" + hr + "&deskripsi=" + d;
new CRUD().execute(url);
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
update.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String url = "";
url = "http://192.168.1.10/crudsederhana/aksi.php";
try {
String ko = URLEncoder.encode(kode.getText().toString(),"utf-8");
String n = URLEncoder.encode(nama.getText().toString(),"utf-8");
String hr = URLEncoder.encode(harga.getText().toString(),"utf-8");
String d = URLEncoder.encode(deskripsi.getText().toString(), "utf-8");
url += "?a=update&kd=" + ko + "&nm=" + n + "&hrg=" +hr+ "&des=" + d;
new CRUD().execute(url);
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "";
kode1 = kode.getText().toString();
url = "http://192.168.1.10/crudsederhana/aksi.php?a=delete&kd=" + kode1;
new CRUD().execute(url);
}
});
cek.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "";
kode1 = kode.getText().toString();
url = "http://192.168.1.10/crudsederhana/aksi.php?a=read&kd="+kode1;
new CRUD().execute(url);
}
});
}
public class CRUD extends AsyncTask<String, String, String> {
String success;
String kode_d, nama_d, harga_d, des_d;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(params[0]);
try {
success = json.getString("success");
Log.e("error", "nilai sukses=" + success);
JSONArray hasil = json.getJSONArray("login");
if (success.equals("1")) {
for (int i = 0; i < hasil.length(); i++) {
JSONObject c = hasil.getJSONObject(i);
kode_d = c.getString("kd");
nama_d = c.getString("nm");
harga_d = c.getString("hrg");
des_d = c.getString("deskripsi");
}
}
else {
Log.e("erro", "tidak bisa ambil data 0");
}
}
catch (Exception e) {
// TODO: handle exception
Log.e("erro", "tidak bisa ambil data 1");
}
return kode_d;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
kode.setText(kode_d);
nama.setText(nama_d);
harga.setText(harga_d);
deskripsi.setText(des_d);
}
}
}
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;
}
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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;
}
}
It is because you don't return any value from the doInBackground() (always return null) and you are not using the 'string' in the onPostExecute(String result) formal parameter. Garbage-In-Garbage-Out
your doInBackground() returns just a string return kode_d; and then in your onPostExecute(String result) (which expects a String) you use the kode_d which is null.
If you want all of those values to be returned create an ArrayList(), return it at the end doInBackground() and get it in onPostExecute(ArrayList result) with an iteration and pass it to you textviews.
Even better create an object and add the values to each field. Your fields are the kode_d, nama_d, harga_d, des_d
this is what the onPostExecute does
/**
* <p>Runs on the UI thread after {#link #doInBackground}. The
* specified result is the value returned by {#link #doInBackground}.
* To better support testing frameworks, it is recommended that this be
* written to tolerate direct execution as part of the execute() call.
* The default version does nothing.</p>
*
* <p>This method won't be invoked if the task was cancelled.</p>
*
* #param result The result of the operation computed by {#link #doInBackground}.
*
* #see #onPreExecute
* #see #doInBackground
* #see #onCancelled(Object)
*/

Unable to solve Json Object code

I want to write a android code to retrieve json array but I cannot do it. I have tried many tutorials but nothing seemed to worked. Please anyone solve this problem.
Here is the Json:
{
"total_records":"3370",
"count":100,
"records": [
{"id":"175274241",
"timestamp":"1494685823",
"state":"Telangana",
"district":"Warangal",
"market":"Mahabubabad",
"commodity":"Cotton",
"variety":"Desi",
"arrival_date":"13/05/2017",
"min_price":"4150",
"max_price":"4150",
"modal_price":"4150" }
]
}
Here is the Android code
public class MainActivity extends Activity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncLogin().execute();
}
private class AsyncLogin extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL("website url");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
pdLoading.dismiss();
try {
List<String> categories = new ArrayList<String>();
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
String str = json_data.getString("records");
Toast.makeText(MainActivity.this,str,Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Toast.makeText(MainActivity.this,""+e,Toast.LENGTH_LONG).show();
}
}
}
}
Anyone write a android code for above json data.
If your json data is in string jsonStr.By the help of following code ,you can parse your json
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String records = jsonObj.getString("total_records");
String count= jsonObj.getString("count");
// Getting JSON Array node
JSONArray records= jsonObj.getJSONArray("records");
// looping through All Contacts
for (int i = 0; i < records.length(); i++) {
JSONObject c = records.getJSONObject(i);
String id = c.getString("id");
String timestamp= c.getString("timestamp");
String state= c.getString("state");
String district= c.getString("district");
String market= c.getString("market");
String commodity= c.getString("commodity");
String variety= c.getString("variety");
String arrival_date= c.getString("arrival_date");
String min_price= c.getString("min_price");
String max_price= c.getString("max_price");
String modal_price= c.getString("modal_price");
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}

ERROR parsing data value of type org.json.JSONArray cannot be converted to JSONObject

While Running the code (given after the error msg) throws the error as
Coding follows:
public class Slide extends ActionBarActivity {
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> detailsList; //Creating a Arraylist
private static String URL = "URL to my php page";
private static final String TAG_DETAILS = "details";
private static final String TAG_TITLE = "title";
JSONArray details = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slide);
new onlineload().execute();
}
class onlineload extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Slide.this);
pDialog.setMessage("Fetching Books...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String title = "";
TextView tvTitle = (TextView)findViewById(R.id.Title);
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(URL, "GET", params);
Log.d("All Products:",json.toString());
try {
details = json.getJSONArray(TAG_DETAILS);
for (int i = 0; i < details.length(); i++) {
JSONObject c = details.getJSONObject(i);
title = title + c.getString(TAG_TITLE)+"\n";
tvTitle.setText(title);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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);
}
}
Shown above is my java code..
Function of this code is to fetch Book title (more than 10 books title is available in database)from the online database and view it in an scroll view activity ..
my php code is working am getting the output only the problem is in displaying it in android activity !!
Looking for some help!!
JSON CODE:
public class JSONParser {
static InputStream is = null;
static JSONArray jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONArray makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
Log.d("Entered Get", "Get SUccess"+url+method);
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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 JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Agree with #ρяσѕρєя K
There was cast exception occurred that means you need to use JSON Array. Coz you are using JSON Object where actually JSON Array is required.
If you are confused within response which is receiving is JSONArray or JSONObject then you can go for get() method which return data in Object manner.
example : Object c = details.get(i);
So after that you can check for
If(c instanceOf JSONArray){
/// perform as array operation
}
If(c instanceOf JSONObject){
// perform json object retrieving operation
}

Error when parsing json result from http post on android app

I have a php script that returns this json array.
{"PID":"1","PName":"Guitar","Brand":"Fender","Price":"110","Cat#":"1","Typ#":"1"}
I am making a simple app that places these results into several text views. only one product is returned each time as above.
when I run the app I get this Error: org.json.JSONException: Value
{"Typ#":"1","Brand":"test","Cat#":"1","PName":"Test","PID":"2","Price":"120"}
of type org.json.JSONObject cannot be converted to JSONArray.
Here is my code. Is there something wrong with the json result or the code?
public class MainActivity extends ActionBarActivity {
TextView tvname;
TextView tvbrand;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvname = (TextView) findViewById(R.id.tvName);
tvbrand = (TextView) findViewById(R.id.tvBrand);
Button btnPost = (Button) findViewById(R.id.btnPost);
btnPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new getPro().execute();
}
});
}//end of on create
private class getPro extends AsyncTask<String,String,Void>{
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream inputStream = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
getPro.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... strings) {
String url_select = "http://10.0.2.2/OnetoOne/getProduct.php";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("pid", "2"));
try {
// Set up HTTP post
// HttpClient is more then less deprecated. Need to change to URLConnection
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// Read content & Log
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
//parse JSON data
try {
JSONArray jArray = new JSONArray(result);
//JSONObject jObject = jArray.getJSONObject(0);
String anem = jArray.getJSONObject(0).getString("PName");
//String getname = jObject.getString("PName");
//String getbrand = jObject.getString("Brand");
tvname.setText(anem);
//tvbrand.setText(getbrand);
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
}
}
}//end of async
}//end of class
Any help would be greatly appreciated.
That's not an array it's an object
JSONObject jObject = new JSONObject(result);
String anem = jObject.getString("PName");
tvname.setText(anem);
{"Typ#":"1","Brand":"test","Cat#":"1","PName":"Test","PID":"2","Price":"120"} of type org.json.JSONObject cannot be converted to JSONArray.
You are trying to convert a JSONObject into a JSONArray, this is your error.
Use :
JSONOjbect jso = new JSONObject(result);
A JSONObject Start with { and end with }.
A JSONArray Start with [ and end with ].

json parsing from url in android project

how to get text from json without [" "] only text ,in android project
this is my json from url {"code":200,"lang":"en-ru","text":["Better late than never"]}
i need get text "text":["Better late than never"] without [" "] only text: Better late than never
myclass MAINACTIVITY
public class MainActivity extends Activity {
JSONParser jsonparser = new JSONParser();
TextView tv;
String ab;
JSONObject jobj = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tvResult);
new retrievedata().execute();
}
class retrievedata extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
jobj = jsonparser.makeHttpRequest("https://translate.yandex.net/api/v1.5/tr.json/translate?key=YOURAPIKEY&text=Better%20late%20than%20never&lang=ru");
// check your log for json response
Log.d("Login attempt", jobj.toString());
ab = jobj.optString("text");
return ab;
}
protected void onPostExecute(String ab){
tv.setText(ab);
}
}
}
MY JSONPARSER CLASS
public class JSONParser {
static InputStream is = null;
static JSONObject jobj = null;
static String json = "";
public JSONParser(){
}
public JSONObject makeHttpRequest(String url){
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity httpentity = httpresponse.getEntity();
is = httpentity.getContent();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
try {
while((line = reader.readLine())!=null){
sb.append(line+"\n");
}
is.close();
json = sb.toString();
try {
jobj = new JSONObject(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jobj;
}
}
From your json from url {"code":200,"lang":"en-ru","text":["Better late than never"]}
Try this...
Yout JSON structure
{
"code": 200,
"lang": "en-ru",
"text": [
"Better late than never"
]
}
You can get your output using below..
try {
JSONObject jsonObj = new JSONObject(json);
String code = jsonObj.getString("code");
String lang = jsonObj.getString("lang");
JSONArray text = jsonObj.getJSONArray("text");
Log.e("output", "code:" + code + "\nlang:" + lang + "\ntext"
+ text.getString(0));
} catch (Exception e) {
e.printStackTrace();
}
replace
ab = jobj.optString("text");
with
JSONArray txt = jobj.getJSONArray("text");
ab=txt.getString(0);

Categories