I am coding an android app for school atm. i am stock and want to ask you guy to help me.
So far i understand how to use PHP to print data from a MySQL database ready to be parset in Java. Then my code(taken from here: http://www.helloandroid.com/tutorials/connecting-mysql-database)takes the data and converts it into strings i believe.
So my question is: how do i for eksample make and if statement to check if the userdata is correct? i just dont get it!
Here is all my code for the activity(login form) i use:
package com.example.fungi;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
//Intent i = new Intent(getBaseContext(), MainPageActivity.class);
//startActivity(i);
Button login;
EditText username;
EditText password;
TextView lol;
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ActionBar actionBar = getActionBar();
//actionBar.hide();
lol = (TextView) findViewById(R.id.textView1);
login = (Button) findViewById(R.id.loginbutton);
username = (EditText) findViewById(R.id.usernametext);
password = (EditText) findViewById(R.id.passwordtext);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String usernameget = username.getText().toString();
String passwordget = password.getText().toString();
if(usernameget.contentEquals("")){
username.setText("usernam required");
}else {
if(passwordget.contentEquals("")){
username.setText("password required");
}else {
String userid = username.getText().toString();
Intent intent = new Intent(getBaseContext(), Side.class);
intent.putExtra("sessionid", userid);
startActivity(intent);
}
}
}
});
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair(result, result));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://http://fungi.webatu.com/Index.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
}catch(Exception e11){
Log.e("log_tag", "Fejl i HTTP connection "+e11.toString());
}
//convert response to string
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();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Fejl i resultat konvertering "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("id")+
", username: "+json_data.getString("username")+
", password: "+json_data.getString("password")+
", alder: "+json_data.getInt("alder"));
//maybe if statement here?
;
}
}
catch(JSONException e1){
Log.e("log_tag", "Error parsing data "+e1.toString());
}
}
}
thanks in advance!!
I'm not sure about your issue, but I think you want to get some JSON data from a webservice.
Developing to Android, you cannot use network resources on the main thread. So you will need to start a new thread. To reach that, you can use AsyncTask or use the Thread class.
public static JSONArray getJSONArrayFromURL(String url) {
// initialize
InputStream is = null;
String result = "";
JSONArray jArray = null;
Log.d("URL_SEARCH", url);
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jArray = new JSONArray(result);
Log.d("URL_SEARCH", "JSON: " + jArray.length());
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
Related
i am just a beginner in developing android applications, i wanted to connect my application to a server so i could get data from MySQL. so i tried to make login part first but i have some problems. my code doesn't work for reading JSON.
my codes are as below:
LoginActivity(MainActivity) :
package ir.naserpour.sportclub;
import android.content.Context;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class LoginActivity extends AppCompatActivity {
String link;
String response;
//get values
String username,password;
#Override
protected void attachBaseContext (Context newBase){
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//define things
TextView menu = (TextView) findViewById(R.id.menu);
final EditText login_username = (EditText) findViewById(R.id.login_username);
final EditText login_password = (EditText) findViewById(R.id.login_password);
Button login_login = (Button) findViewById(R.id.login_login);
Button login_register = (Button)findViewById(R.id.login_register);
CheckBox rememberme = (CheckBox)findViewById(R.id.login_remeberme);
//set icon type face
Typeface fonticon = Typeface.createFromAsset(getAssets(), "fonts/icon.ttf");
menu.setTypeface(fonticon);
login_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
username = login_username.getText().toString();
password = login_password.getText().toString();
//check values
if (username.length() <1 || password.length() < 1) {
Toast.makeText(getApplicationContext(), "fields cannot be empty", Toast.LENGTH_SHORT).show();
} else {
//generate link
link = "http://localhost:8080/login.php?username="+username+"&password="+password;
login();
if(response=="true"){
Toast.makeText(getApplicationContext(), "true", Toast.LENGTH_SHORT).show();
}else if(response=="false"){
Toast.makeText(getApplicationContext(), "false", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "response", Toast.LENGTH_SHORT).show();
}
}
}
});
}
#Override
protected void onPause () {
super.onPause();
finish();
}
public String login() {
new JSONParse().execute();
return response;
}
public class JSONParse extends AsyncTask<String, String, JSONObject> {
#Override
public void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplicationContext(),"getting data ...",Toast.LENGTH_SHORT).show();
}
#Override
public JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(link);
return json;
}
#Override
public void onPostExecute(JSONObject json) {
try {
JSONArray result = json.getJSONArray("result");
JSONObject c = result.getJSONObject(0);
try {
String res = new String(c.getString("response").getBytes("ISO-8859-1"), "UTF-8");
response = res;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser.java:
package ir.naserpour.sportclub;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
/**
* Created by Mohammad Naserpour on 9/22/2016.
*/
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;
}
}
and also my login.php script:
<?php
define("HOST","localhost");
define("USERNAME","root");
define("PASSWORD","");
define("NAME","users");
$con = mysqli_connect(HOST,USERNAME,PASSWORD,NAME);
$username = $_GET["username"];
$password = $_GET["password"];
$sql = "SELECT * FROM userinfo WHERE username ='$username' AND password='$password'";
$check = mysqli_fetch_array(mysqli_query($con,$sql));
if(isset($check)){
echo '{"result":[{"response":"true"}]}';
}else{
echo '{"result":[{"response":"false"}]}';
}
mysqli_close($con);
?>
i would be so happy if i find out the problem. thank you.
see this tutorial :
its a full tutorial about login process using google volley
First : On device side, Use volley, its simple and easy to use
Second : On server, what is {"result":[{"response":"true"}]}
any problem with {"result":true} ??
Last but not the least : Did you use JSON before or this code is trial and error copy paste from some tutorials?
I am trying to develop a simple client-server application in Android. I have a problem while fetching a response from PHP code. It returns an HTML code instead of JSON. Is it a problem with the WAMP server I have used?
Here is the PHP code:
<?php
include_once './connect_db.php';
$db = new DBConnect();
$response = array();
$username = $_POST["username"];
$password = $_POST["password"];
if (empty($_POST['username']) || empty($_POST['password']))
{
$response["success"] = 0;
$response["message"] = "One or both of the fields are empty.";
die(json_encode($response));
}
$query = " SELECT * FROM account WHERE username = '$username'and password='$password'";
$sql1 = mysql_query($query);
$row = mysql_fetch_array($sql1);
if (!empty($row))
{
$response["success"] = 1;
$response["message"] = "You have been sucessfully login";
die(json_encode($response));
}
else
{
$response["success"] = 0;
$response["message"] = "invalid username or password ";
die(json_encode($response));
}
mysql_close();
?>
login.java:
package com.example.rossh.register;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class login extends AppCompatActivity implements OnClickListener {
private EditText user, pass;
private Button login;
JSONObject jsonObject;
String response;
// Progress Dialog
private ProgressDialog pDialog;
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//setup input fields
user = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
//setup buttons
login = (Button) findViewById(R.id.btnlogin);
//register listeners
login.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnlogin:
String username = user.getText().toString();
String password = pass.getText().toString();
boolean cancel =false;
View focusView = null;
if(TextUtils.isEmpty(username))
{
user.setError("This field is required!!");
cancel=true;
focusView=user;
}
if(TextUtils.isEmpty(password))
{
pass.setError("This field is requird!!!");
cancel=true;
focusView=pass;
}
if(cancel)
{
focusView.requestFocus();
} else {
new AttemptLogin().execute(username, password);
}
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(login.this);
pDialog.setMessage("Attempting login...");
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
String username = args[0];
String password = args[1];
// Building Parameters
final int success;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JsonParser jsonParser = new JsonParser();
jsonObject = jsonParser.makeHttpRequest(AppConfig.LOGIN_URL, "POST", params);
if (jsonObject != null) {
try{
Log.d("Json data",">"+jsonObject);
success = jsonObject.getInt(TAG_SUCCESS);
if (success == 1) {
response = jsonObject.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", jsonObject.getString(TAG_MESSAGE));
response = jsonObject.getString(TAG_MESSAGE);
}
} catch(JSONException e) {
e.printStackTrace();
}
}
return response;
}
/**
* After completing background task Dismiss the progress dialog
**/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null) {
Toast.makeText(login.this, "ok", Toast.LENGTH_LONG).show();
}
}
}
}
}
jsonParser.java:
package com.example.rossh.register;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.widget.Toast;
public class JsonParser {
InputStream is = null;
static String json = "";
static JSONObject jObj = null;
// constructor
public JsonParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
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));
httpPost.setHeader("Content-Type","application/json");
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, HTTP.UTF_8), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.d("String",">"+json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
JSONArray jsonarray = new JSONArray(json);
jObj = jsonarray.getJSONObject(0);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing " + e.toString());
}
// return JSON String
return jObj;
}
}
It may be due to one or more errors in your HTML, or if your page returns non-text objects. Make sure your HTML webpage does not throw an error while running from browser.
For one thing I would suggest that your PHP script sets proper content type when returning json, see Returning JSON from a PHP Script. Also see Java HttpRequest JSON & Response Handling for how to do JSON requests in java.
Try changing die(json_encode($response)) to echo json_encode($response)
This is Attendance.java file
package com.glbwebsim;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;`
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TableRow.LayoutParams;
public class Attendance extends Activity
{
static InputStream iStream = null;
static JSONArray jArray = null;
static String json = "";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main7);
Button details = (Button) findViewById(R.id.mydetails);
details.setOnClickListener(new View.OnClickListener()
{
#SuppressWarnings({ "deprecation", "unused" })
public void onClick(View view)
{
String result = null;
InputStream is = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://frndz4ever.com/glbsim/attend.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("log_tag", "connection success ");
// Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
}
//convert response to string
StringBuilder sb = new StringBuilder();
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
// Toast.makeText(getApplicationContext(), "Input Reading pass", Toast.LENGTH_SHORT).show();
}
is.close();
result=sb.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();
}
//parse json data
try
{
JSONArray jArray = new JSONArray("["+result+"]");
String re=jArray.getString(jArray.length()-1);
TableLayout tv=(TableLayout) findViewById(R.id.table);
tv.removeAllViewsInLayout();
int flag=1;
for(int i=0;i<re.length();i++)
{
TableRow tr=new TableRow(Attendance.this);
tr.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
if(flag==1)
{
TextView b6=new TextView(Attendance.this);
b6.setText("Roll_no");
b6.setTextColor(Color.BLACK);
b6.setTextSize(18);
tr.addView(b6);
TextView b19=new TextView(Attendance.this);
b19.setPadding(10, 0, 0, 0);
b19.setTextSize(18);
b19.setText("Subjects");
b19.setTextColor(Color.BLACK);
tr.addView(b19);
TextView b29=new TextView(Attendance.this);
b29.setPadding(10, 0, 0, 0);
b29.setText("Present");
b29.setTextColor(Color.BLACK);
b29.setTextSize(18);
tr.addView(b29);
TextView b30=new TextView(Attendance.this);
b30.setPadding(10, 0, 0, 0);
b30.setText("Absent");
b30.setTextColor(Color.BLACK);
b30.setTextSize(18);
tr.addView(b30);
tv.addView(tr);
final View vline = new View(Attendance.this);
vline.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 2));
vline.setBackgroundColor(Color.BLUE);
tv.addView(vline);
}
else
{
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","Roll_no: "+json_data.getInt("Roll_no")+
", Subjects: "+json_data.getString("Subjects")+
", Present: "+json_data.getInt("Present")+
",Absent: "+json_data.getInt("Absent"));
TextView b=new TextView(Attendance.this);
String stime=String.valueOf(json_data.getInt("Roll_no"));
b.setText(stime);
b.setTextColor(Color.RED);
b.setTextSize(15);
tr.addView(b);
TextView b1=new TextView(Attendance.this);
b1.setPadding(10, 0, 0, 0);
b1.setTextSize(15);
String stime1=json_data.getString("Subjects");
b1.setText(stime1);
b1.setTextColor(Color.WHITE);
tr.addView(b1);
TextView b2=new TextView(Attendance.this);
b2.setPadding(10, 0, 0, 0);
String stime2=String.valueOf(json_data.getInt("Present"));
b2.setText(stime2);
b2.setTextColor(Color.RED);
b2.setTextSize(15);
tr.addView(b2);
TextView b3=new TextView(Attendance.this);
b3.setPadding(10, 0, 0, 0);
String stime3=String.valueOf(json_data.getInt("Absent"));
b3.setText(stime2);
b3.setTextColor(Color.RED);
b3.setTextSize(15);
tr.addView(b3);
tv.addView(tr);
final View vline1 = new View(Attendance.this);
vline1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 1));
vline1.setBackgroundColor(Color.WHITE);
tv.addView(vline1);
}
}}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
}
return;
}
});
}}
I'm getting JsonArray fail error on click of the button.
Please help.
LogCat:
04-20 20:54:37.458: D/StrictMode(9281): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1151) 04-20 20:54:37.458: D/StrictMode(9281): at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:163) 04-20 20:54:37.458: D/StrictMode(9281): at libcore.io.IoBridge.recvfrom(IoBridge.java:506)
See the code below for reference, it might have errors, its just to get an ides how it works.
Any network activity should be performed in doInBackground.
Do not perform any action on UI.
Once the doInBackground is complete, the data is returned to onPostExecute.
Now you can perform your UI actions here.
public class Attendance extends Activity {
static InputStream iStream = null;
static JSONArray jArray = null;
static String json = "";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button details = (Button) findViewById(R.id.mydetails);
details.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings({ "deprecation", "unused" })
public void onClick(View view) {
new makeHTTPRequest().execute();
}
});
}
private class makeHTTPRequest extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String result = null;
InputStream is = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://frndz4ever.com/glbsim/attend.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.i("log_tag", "connection success ");
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
// Toast.makeText(getApplicationContext(), "Connection fail",
// Toast.LENGTH_SHORT).show();
}
// convert response to string
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
protected void onPostExecute(String result) {
// parse json data
try {
JSONArray jArray = new JSONArray(result);
String re = jArray.getString(jArray.length() - 1);
int flag = 1;
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(0);
Log.i("log_tag",
"Index: "+ i + " Roll_no: " + json_data.getInt("Roll_no")
+ ", Subjects: "
+ json_data.getString("Subject")
+ ", Present: "
+ json_data.getInt("Present")
+ ",Absent: "
+ json_data.getInt("Absent"));
}
// Perform any required actions here
}
catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
}
}
}
}
I have updated the private class makeHTTPRequest
dont forget to add
<uses-permission android:name="android.permission.INTERNET" />
under the uses-sdk tag
And this is the Logcat output:
04-21 23:37:13.904: I/log_tag(14032): Index: 0 Roll_no: 70, Subjects: Multimedia, Present: 20,Absent: 10
04-21 23:37:13.905: I/log_tag(14032): Index: 1 Roll_no: 70, Subjects: Multimedia, Present: 20,Absent: 10
04-21 23:37:13.905: I/log_tag(14032): Index: 2 Roll_no: 70, Subjects: Multimedia, Present: 20,Absent: 10
04-21 23:37:13.905: I/log_tag(14032): Index: 3 Roll_no: 70, Subjects: Multimedia, Present: 20,Absent: 10
First try this, if it works, add code step by step to enhance your app.
I am new to android. Well what I am trying to do in the following code is making an http request sending to a php file from where json gets the response. In the php file I am trying to show the city names starting from A. Whenever I am running the code I am getting this error: "org.json.jsonexception value doctype of type java.lang.string cannot be converted to jsonarray". All The related Threads are of no help or i am not able to understand the solution given there.
Here is my Java Code
MainActivity.java
package com.list;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.net.ParseException;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb=null;
int ct_id;
String ct_name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textview1 = (TextView)findViewById(R.id.textView1);
textview1.setText("Erqem");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/city.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
try{
jArray = new JSONArray(result);
JSONObject json_data = new JSONObject();
json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getInt("CITY_ID");
ct_name=json_data.getString("CITY_NAME");
textview1.setText(ct_name);
}
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "No City Found"+e1.toString() ,Toast.LENGTH_LONG).show();
Log.e("log_tag", "Error converting result "+e1.getMessage() );
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
php file
<?php
header('Content-type=application/json; charset=utf-8');
mysql_connect("","root","");
mysql_select_db("Deal");
$sql=mysql_query("select * from CITY where CITY_NAME like 'A%'");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
Any Help would be appreciated.Thanks.
maybe you are using incorrect address, please try 10.0.2.2:8080/city.php
My java code:
package com.Cmode.ThesisSystem;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.net.ParseException;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class EventLogs extends ListActivity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb=null;
int e_id;
String e_name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();{
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.my.com/eventlogs.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
e_id=json_data.getInt("id");
e_name=json_data.getString("event");
}
}catch(JSONException e1){
Toast.makeText(getBaseContext(), "No events found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
}
I have a problem with this code
Error:
The application CDroidMonitoring(process.com.Cmode.ThesisSystem) has stopped unexpectedly. Please try again
Im just new to android development. I think I have put something unusable braces or there is something wrong in the code.
Does your application have the INTERNET permission set in the manifest?
And for more information about the error check the logcat tab in Eclipse, it usually has a more descriptive error message.