How to display Questions and Choices? - java

Im working on an Android Application that needed to display a Question(TextView) and Four possible answers(RadioGroup with RadioButtons). Im using a Web Server and MySql for connecting the database into my app. In order to get the data i converted the data into JSON using this method in PHP.
<?php
include_once 'db.php';
class Quiz{
private $db;
private $db_table = "aenglish_questions";
public function __construct(){
$this->db = new DbConnect();
}
public function getAllQuizQuestions(){
$json_array = array();
$query = "select * from aenglish_questions";
$result = mysqli_query($this->db->getDb(), $query);
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_assoc($result)) {
$json_array["quiz_questions"][] = $row;
}
}
return $json_array;
}
}
?>
After getting the JSON data, i needed to display the first question and choices in the textview and radiobuttons in Android studio and when i click the next button it proceeds to the next question.
I`ve try this code and im getting an error message that says my ArrayList is empty.
private class AsyncJsonObject extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httpPost = new HttpPost("http://192.168.1.11/LETIA/includes/index.php");
String jsonResult = "";
try {
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
System.out.println("Returned Json object " + jsonResult.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonResult;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = ProgressDialog.show(getActivity(), "Downloading Quiz","Wait....", true);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
System.out.println("Resulted Value: " + result);
parsedObject = returnParsedJsonObject(result);
if(parsedObject == null){
return;
}
quizCount = parsedObject.size();
firstQuestion = parsedObject.get(0);
quizQuestion.setText(firstQuestion.getQuestion());
String[] possibleAnswers = firstQuestion.getAnswers().split(",");
optionOne.setText(possibleAnswers[0]);
optionTwo.setText(possibleAnswers[1]);
optionThree.setText(possibleAnswers[2]);
optionFour.setText(possibleAnswers[3]);
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
}
I dont know what is the problem and im trying to find an answer for a couple of hours. I just needed it to get pass on my project and any help you provide will have a big impact in my study. Hope you guys can help me.
This is my code on putting the JSON into an ArrayList.
private List<QuizWrapper> returnParsedJsonObject(String result){
List<QuizWrapper> jsonObject = new ArrayList<QuizWrapper>();
JSONObject resultObject = null;
JSONArray jsonArray = null;
QuizWrapper newItemObject = null;
try {
resultObject = new JSONObject(result);
System.out.println("Testing the water " + resultObject.toString());
jsonArray = resultObject.optJSONArray("aenglish_questions");
} catch (JSONException e) {
e.printStackTrace();
}
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonChildNode = null;
try {
jsonChildNode = jsonArray.getJSONObject(i);
int id = jsonChildNode.getInt("qae_id");
String question = jsonChildNode.getString("question");
String answerOptions = jsonChildNode.getString("choices");
int correctAnswer = jsonChildNode.getInt("answer");
newItemObject = new QuizWrapper(id, question, answerOptions, correctAnswer);
jsonObject.add(newItemObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonObject;
}
Im having this Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.pre_boardreviewer, PID: 26290
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at com.example.recall.EnglishFragments.Question10Fragment$AsyncJsonObject.onPostExecute(Question10Fragment.java:164)
at com.example.recall.EnglishFragments.Question10Fragment$AsyncJsonObject.onPostExecute(Question10Fragment.java:123)
at android.os.AsyncTask.finish(AsyncTask.java:695)
at android.os.AsyncTask.access$600(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7156)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)

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();
}

Nullpointer exception comes in onpostexcute [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Plz help me
When we get data from server and save in a string variable, it is store in a variable but cantnot retrive.
public class Profile extends Activity {
ListView list;
Activity act;
String[] username = { "Pankaj", "Aaa" };
TextView name;
JSONObject object;
String url = "http://thinksl.com/taughtable/profile.php?user_email=pank#gmail.com";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
list = (ListView) findViewById(R.id.list);
name = (TextView) findViewById(R.id.mailid);
Custom_Profile pro = new Custom_Profile(Profile.this, username);
list.setAdapter(pro);
new Userdata().execute(url);
}
public class Userdata extends AsyncTask<String, Void, String> {
public static final int connection_type = 1500;
Profile p = new Profile();
ProgressDialog dialog;
String resul;
HashMap<String, String> user;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog = new ProgressDialog(Profile.this);
dialog.setTitle("Processing");
dialog.setMessage("Loading Data.Please wait....");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected String doInBackground(String... url) {
// TODO Auto-generated method stub
Log.e("result", "Do in background");
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, connection_type);
HttpConnectionParams.setSoTimeout(params, connection_type);
HttpClient client = new DefaultHttpClient(params);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("user_email", "pank#gmail.com"));
HttpGet get = new HttpGet(url[0]);
try {
Log.e("result", "Try");
HttpResponse response = client.execute(get);
Log.e("result", "Response" + response);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
Log.e("result", "result" + result);
JSONObject jobject = new JSONObject(result);
object = jobject.getJSONObject("userdetail");
Log.e("result", "result" + object);
String name = object.getString("user_login");
int post = object.getInt("month");
Log.e("name", "name" + name);
Log.e("name", "post" + post);
Log.e("result", "result" + resul);
user = new HashMap<String, String>();
user.put("name", name);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
String s = user.get("name").toString();
p.name.setText(s);
}
}
}
The problem is that you are returning always null, after catch you have the only returning.
Look the last line of doinbackground method, "returning null".
So change to this:
HttpGet get = new HttpGet(url[0]);
HttpResponse response = client.execute(get);
Log.e("result", "Response" + response);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
return result;
And in the postexecute method do it:
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
JSONObject jobject = new JSONObject(result);
object = jobject.getJSONObject("userdetail");
Log.e("result", "result" + object);
String name = object.getString("user_login");
int post = object.getInt("month");
Log.e("name", "name" + name);
Log.e("name", "post" + post);
Log.e("result", "result" + resul);
user = new HashMap<String, String>();
user.put("name", name);
dialog.dismiss();
String s = user.get("name").toString();
p.name.setText(s);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
use this code
JSONObject res = new JSONObject(result);
JSONObject response = res.getJSONObject("userdetail");
String niceName = response.getString("user_nicename");
String displayName = response.getString("display_name");

Displaying database records in android using JAVA RESTful webservice

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

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 ].

Categories