Parse JSONArray in Android Studio - java

I try to get parse an JSONArray from a PHP-Script in AndroidStudio. I get this JSON Response from my PHP script:
[{"0":"Firstname","meta_value":"Firstname"},{"0":"Lastname","meta_value":"Lastname"},{"valid":"1"},{"entered":"5"}]
Now I try to parse the JSONArray to get the value meta_value so I want to get "Lastname" and "Firstname".
But there must be an error in my code because I get as response: Exception: No value for meta_value
public class SendPostRequest extends AsyncTask<String, Void, String> {
String data ="";
String dataParsed = "";
String singleParsed ="";
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try {
URL url = new URL("https://sample.com/code2.php"); // here is your URL path
JSONObject postDataParams = new JSONObject();
postDataParams.put("sdata", scannedData);
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new
InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
data = data + line;
sb.append(line);
break;
}
in.close();
JSONArray reader2 = new JSONArray(data);
for(int i =0 ;i <reader2.length(); i++){
JSONObject JO = (JSONObject) reader2.get(i);
singleParsed = "Name:" + JO.get("meta_value") + "\n";
dataParsed = dataParsed + singleParsed +"\n" ;
}
return dataParsed;
}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
}
Please dont mark my Answer as duplicate because I searched for 2 weeks and but havent found an Answer! Thank you:)

I would suggest you to use GSON for serializing and deserializing your JSON responses. It makes it quite easy to handle then. GSON.
Sample:
new Gson().fromJson("YourJsonHere",JsonElement.class);
Cheers Tarik

Related

Buffered reader return null (can not get data from SQL server)

I wrote this code to make a connection and I used AsyncTask class BufferedReader with JSON object and JSON Array, but the bufferedReader return null every time, I tried the API by Fiddler (HTTP debugging server) and it is worked correctly.
//class AsyncTask
class GetUserList extends AsyncTask<String, Void, String> {
String status= null;
public GetUserList(){
}
protected void onPreExecute(){
}
#SuppressLint("WrongThread")
protected String doInBackground(String... connUrl){
HttpURLConnection conn=null;
BufferedReader reader;
final URL url;
int result;
InputStream in;
String line;
try{
url=new URL(connUrl[0]);
conn=(HttpURLConnection) url.openConnection();
conn.addRequestProperty("Content-Type", "application/json; charset=utf-8");
conn.setRequestMethod("GET");
result = conn.getResponseCode();
if(result == 200){
in=new BufferedInputStream(conn.getInputStream());
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb=new StringBuilder();
line = null;
while((line=reader.readLine())!=null){
status=line;
}
}
}catch(Exception ex){
ex.printStackTrace();
}
return status;
}
protected void onPostExecute(String result){
super.onPostExecute(result);
JSONArray jsonArray;
JSONObject object;
String User;
int i =0;
if(result!=null){
try{
jsonArray = new JSONArray(result);
for( i=0; i<jsonArray.length(); i++){
object = jsonArray.getJSONObject(i);
User= object.getString("User");
}//end for
}//end try
catch (Exception ex){
ex.printStackTrace();
}//end catch
}//end if
}
}

Android app, HttpURLConnection GET method, AsyncTask getting tag instead of result

It is simple app that needs to send two numbers using GET and reads back.
Button btnSaberi;
EditText txtAunos, txtBunos;
TextView txtIspis;
String sturl = "http://xxx.xxx.xx.x/PhpProject1/index.php";
Integer a, b;
HttpURLConnection httpURLConnection;
URL url;
public void posalji(View view){
a = Integer.parseInt(txtAunos.getText().toString());
b = Integer.parseInt(txtBunos.getText().toString());
sturl = sturl+"?a=" + a + "&b=" + b;
new Posalji().execute(sturl);
}
class Posalji extends AsyncTask<String, String, String> {
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
txtIspis.setText("Rezultat je : " + s);
}
#Override
protected String doInBackground(String... strings) {
try {
url = new URL(strings[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
rez = br.readLine();
}
return rez;
}
}
}
Using Emulator.
I have changed and now instead of showing me php output it shows me html tag.
"<!DOCTYPE html>"
Please remove txtIspis.setText("Rezultat je : " + br.readLine()); line from AsyncTask doInBackground. In doInBackground we never update UI like this. you can use onPostExecute for update your textbox values.
Please read this doc https://developer.android.com/reference/android/os/AsyncTask
As you are calling br.readLine(); just once, it is reading only the first line of data from the BufferedReader.
To read all the lines of data from BufferedReader you need to use a loop.
Update your doInBackground method
#Override
protected String doInBackground(String... params){
String url = params[0];
String result;
try {
URL myUrl = new URL(url);
HttpURLConnection connection =(HttpURLConnection) myUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect()
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
String inputLine;
while((inputLine = reader.readLine()) != null){
stringBuilder.append(inputLine);
}
reader.close();
streamReader.close();
result = stringBuilder.toString();
}
return result;
}

Android cannot read http post response from flask server

I just wrote a simple server with flask and send a http post requset to the server from an Android App. But I failed to read the response in the Android App. The app throw an exception:
My flask code is:
#app.route('/zsj',methods = ['POST'])
def show_data():
data = request.get_json()
print request.values #json.loads(data)#request.get_json()
#data = json
#print data
return "aaaa"#jsonify({'w':'u'})
My android App just use the HttpURLConnection class to send a post and get a respones from the server, which is expected as a string: 'aaaa'. We tried to read out the string but failed.
And my Android code is
public class SendPostRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try{
// Connect to the server
URL url = new URL("http://ec2-35-164-172-186.us-west-2.compute.amazonaws.com:5000/zsj");
JSONObject postDataParams = new JSONObject();
// Display command
postDataParams.put("Weather", "email");
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(3000);
conn.setConnectTimeout(3000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
responseMessage = conn.getResponseMessage();
int responseCode=conn.getResponseCode();
responseCode2=responseCode;
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new
InputStreamReader(
conn.getInputStream()));
// jtest=conn.getInputStream().read(data);
BufferedReader er=new BufferedReader(new
InputStreamReader(
conn.getErrorStream()));
StringBuffer sb = new StringBuffer("");
String line="";
StringBuffer sb2 = new StringBuffer("");
// in.readLine();
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
// jtest="abc";
// jtest=sb.toString();
while((line = er.readLine()) != null) {
sb2.append(line);
break;
}
in.close();
er.close();
return sb.toString();
}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
My App code just throw an exception at
BufferedReader er=new BufferedReader(new
InputStreamReader(
conn.getErrorStream()));
Anyone knows how to solve the problem

Android HttpURLConnection POST not working

I have a problem with the parameters passed to an URL by POST. When in PHP i try to retrieve them it says that $_POST is empty:
<?php
require_once 'credentials.php';
$connection = mysqli_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASS, MYSQL_DATABASE);
$query = 'INSERT INTO ratings (disco, rating) VALUES (' .mysqli_real_escape_string($connection, $_POST["disco"]). ', ' . mysqli_real_escape_string($connection, $_POST["rating"]) . ')';
$result = mysqli_query($connection, $query);
echo json_encode($result);
mysqli_close($connection);
?>
And my Android code looks like this:
#Override
protected String doInBackground(String... params) {
String response = "";
try {
URL url = new URL(params[0]);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(10000);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("disco", params[1]));
parameters.add(new BasicNameValuePair("rating", params[2]));
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(getQuery(parameters));
writer.flush();
writer.close();
outputStream.close();
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while((line = br.readLine()) != null) {
response += line;
}
}
} catch(Exception e) {
System.out.println(e.getMessage());
}
return response;
}
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(NameValuePair pair : params) {
if(first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
What's wrong with this? Thanks in advance
Edit: updated code and still doesn't work.
"&disco="
Make that:
"disco="

org.json.JSONException: Value Exception of type java.lang.String cannot be converted to JSONArray

I got this Excepion for two days
"org.json.JSONException: Value Exception of type java.lang.String cannot be converted to JSONArray",
I searched the net but I can't resolve it.
It gives me the desirable response in the browser but I don't know what's the matter with android !
Please help me.
Here is my code
private class SigninActivity extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... arg0) {
String newString="";
try {
String tonTexte = loginDisplay.getText().toString();
String tonTexte1 = passDisplay.getText().toString();
String link = "http://192.168.56.1/projects/stage/atelier.php";
String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(tonTexte, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(tonTexte1, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
sb.append(line);
break;
}
return sb.substring(sb.indexOf("{"),sb.lastIndexOf("}") + 1);
}
catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
TextView a = (TextView) findViewById(R.id.aff);
JSONObject json_data=null;
TextView b = (TextView) findViewById(R.id.aff1);
//recuperation des donnees json
try{
//String jsonObjRecv = JSONGet.getJSONfromURL(URL_LIST);
if(!TextUtils.isEmpty(result)) {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
Log.i("log_tag", "cin: " + json_data.getString("nom"));
donnees.add(json_data.getString("nom"));
donnees1.add(json_data.getString("atelier"));
}
for (String elem : donnees) {
a.setText(elem);
}
for (String elem : donnees1) {
b.setText(elem);
}
}
else{
Log.w("json", "result is null");
}
}
catch(JSONException e){
Log.i("tagjsonexp",""+e.toString());
}
catch (ParseException e) {
Log.i("tagjsonpars", "" + e.toString());
}
}
}
and here is the php code
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$base = mysql_connect ('localhost', 'root', '');
mysql_select_db ('stage', $base) ;
$output=array();
$username = $_POST['username'];
$password = $_POST['password'];
$sql=mysql_query("SELECT CIN FROM authentification where login= '".$username."' AND password = '".$password. "'");
//$sql=mysql_query("SELECT CIN FROM authentification where login= 'amani' AND password = '123' ");
if (!$sql) {
die(mysql_error());
}
while($data = mysql_fetch_array($sql))
{
$a=$data['CIN'];
}
$sql1=mysql_query("SELECT nom,atelier FROM controlleur where CIN= '".$a."'");
while($row=mysql_fetch_assoc($sql1))
{
$output[]=$row;
//print(json_encode(array($output));
print(json_encode(array("NomTableau" => $output)));
mysql_close();
?>
Assuming your PHP script is producing correct JSON. Try changing this part
JSONArray jArray = new JSONArray(result);
to this.
JSONObject jObject = new JSONObject(result);
JSONArray jArray = jObject.getJSONArray("NomTableau");

Categories