session handling in android while logging into the server side in php - java

I am trying to do the session handling process in android.
Here I have successfully logged into through android and now i waant to handle the session of the logged in user.
this is my login_suer.java(android part)
package com.iwantnew.www;
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.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class login_user extends Activity{
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText login_email;
EditText login_password;
Button signin;
TextView error_msg;
private static String url_create_signin= "http://10.0.2.2/android_iwant/login_user.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_form);
// Edit Text
login_email = (EditText) findViewById(R.id.login_email);
login_password = (EditText) findViewById(R.id.login_password);
signin = (Button) findViewById(R.id.signin);
error_msg = (TextView) findViewById(R.id.error_msg);
signin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CheckLogin().execute();
}
});
}
class CheckLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(login_user.this);
pDialog.setMessage("Signing in..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
//Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email",login_email.getText().toString()));
params.add(new BasicNameValuePair("password", login_password.getText().toString()));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_signin,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created users
Intent i = new Intent(getApplicationContext(), post_item.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to sign in
error_msg.setText("Incorrect username/password");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
now i need the idea to start session handling in this java file.
and the code of the server side is below: ie login_user.php
<?php
session_start();
// array for JSON response
$response = array();
if(isset($_POST['email']) && isset($_POST['password'])){
$email = $_POST['email'];
$password = $_POST['password'];
// include db handler
require_once 'DB_Functions.php';
$db = new DB_Functions();
$user = $db->getUesrByEmailAndPassword($email, $password);
if ($user != false) {
// user found
// echo json with success = 1
$response["success"] = 1;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
}
?>
the function used in this above php file is i.e getUesrByEmailAndPassword($email, $password)
is below :
public function getUserByEmailAndPassword($email, $password) {
$result = mysql_query("SELECT * FROM users WHERE email = '$email'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
$salt = $result['salt'];
$encrypted_password = $result['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
//return $result;
session_start();
$_SESSION['clientId'] = $result[0];
$_SESSION['logged_in'] = TRUE;
}
} else {
// user not found
return false;
}
}
Please help me to make my code working.
Any help will be appreciated.
Any link containing such problem solution can be helpful for me. thank you!

As far as I can see, your getUserByEmailAndPassword() never returns actual user data after successfull password check. //return $result; is commented out. $user is therefore null, and client receives "Incorrect email or password!" message.
Another thing. For PHP sessions to work, client has to receive and remember its session_id and send it with every request as GET or COOKIE parameter. Looking at your code, I don't see android receiving its session_id. See: http://www.php.net/manual/en/session.idpassing.php
By the way, using unescaped $email in your SQL query directly from POST is a bad idea. See: How can I prevent SQL injection in PHP?

Related

Getting NullPointerException when inputting text in an EditText

An error occurs when searching for a city using the Android application. After I type a city, state, country (for example: New York, New York, US) and press the search button, the app crashes and gives me a NullPointerException.
MainActivity.java
package com.xxxx.weatherviewer;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListView;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
// List of Weather objects representing the forecast
private List<Weather> weatherList = new ArrayList<>();
// ArrayAdapter for binding Weather objects to a ListView
private WeatherArrayAdapter weatherArrayAdapter;
private ListView weatherListView; // displays weather info
// configure Toolbar, ListView and FAB
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// autogenerated code to inflate layout and configure Toolbar
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// create ArrayAdapter to bind weatherList to the weatherListView
weatherListView = findViewById(R.id.weatherListView);
weatherArrayAdapter = new WeatherArrayAdapter(this, weatherList);
weatherListView.setAdapter(weatherArrayAdapter);
// configure FAB to hide keyboard and initiate web service request
FloatingActionButton fab =
findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// get text from locationEditText and create web service URL
EditText locationEditText =
findViewById(R.id.locationEditText);
URL url = createURL(locationEditText.getText().toString());
// hide keyboard and initiate a GetWeatherTask to download
// weather data from OpenWeatherMap.org in a separate thread
if (url != null) {
dismissKeyboard(locationEditText);
GetWeatherTask getLocalWeatherTask = new GetWeatherTask();
getLocalWeatherTask.execute(url);
}
else {
Snackbar.make(findViewById(R.id.coordinatorLayout),
R.string.invalid_url, Snackbar.LENGTH_LONG).show();
}
}
});
}
// programmatically dismiss keyboard when user touches FAB
private void dismissKeyboard(View view) {
InputMethodManager imm = (InputMethodManager) getSystemService(
Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
// create openweathermap.org web service URL using city
private URL createURL(String city) {
String apiKey = getString(R.string.api_key);
String baseUrl = getString(R.string.web_service_url);
try {
// create URL for specified city and imperial units (Fahrenheit)
String urlString = baseUrl + URLEncoder.encode(city, "UTF-8") +
"&units=imperial&cnt=16&APPID=" + apiKey;
return new URL(urlString);
}
catch (Exception e) {
e.printStackTrace();
}
return null; // URL was malformed
}
// makes the REST web service call to get weather data and
// saves the data to a local HTML file
private class GetWeatherTask extends AsyncTask<URL, Void, JSONObject> {
#Override
protected JSONObject doInBackground(URL... params) {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) params[0].openConnection();
int response = connection.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
StringBuilder builder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
catch (IOException e) {
Snackbar.make(findViewById(R.id.coordinatorLayout),
R.string.read_error, Snackbar.LENGTH_LONG).show();
e.printStackTrace();
}
return new JSONObject(builder.toString());
}
else {
Snackbar.make(findViewById(R.id.coordinatorLayout),
R.string.connect_error, Snackbar.LENGTH_LONG).show();
}
}
catch (Exception e) {
Snackbar.make(findViewById(R.id.coordinatorLayout),
R.string.connect_error, Snackbar.LENGTH_LONG).show();
e.printStackTrace();
}
finally {
assert connection != null;
connection.disconnect(); // close the HttpURLConnection
}
return null;
}
// process JSON response and update ListView
#Override
protected void onPostExecute(JSONObject weather) {
convertJSONtoArrayList(weather); // repopulate weatherList
weatherArrayAdapter.notifyDataSetChanged(); // rebind to ListView
weatherListView.smoothScrollToPosition(0); // scroll to top
}
}
// create Weather objects from JSONObject containing the forecast
private void convertJSONtoArrayList(JSONObject forecast) {
weatherList.clear(); // clear old weather data
try {
// get forecast's "list" JSONArray
JSONArray list = forecast.getJSONArray("list");
// convert each element of list to a Weather object
for (int i = 0; i < list.length(); ++i) {
JSONObject day = list.getJSONObject(i); // get one day's data
// get the day's temperatures ("temp") JSONObject
JSONObject temperatures = day.getJSONObject("temp");
// get day's "weather" JSONObject for the description and icon
JSONObject weather =
day.getJSONArray("weather").getJSONObject(0);
// add new Weather object to weatherList
weatherList.add(new Weather(
day.getLong("dt"), // date/time timestamp
temperatures.getDouble("min"), // minimum temperature
temperatures.getDouble("max"), // maximum temperature
day.getDouble("humidity"), // percent humidity
weather.getString("description"), // weather conditions
weather.getString("icon"))); // icon name
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
This is the error message from the stacktrace:
java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
at com.xxxx.weatherviewer.MainActivity.convertJSONtoArrayList(MainActivity.java:171)
at com.xxxx.weatherviewer.MainActivity.access$300(MainActivity.java:30)
at com.xxxx.weatherviewer.MainActivity$GetWeatherTask.onPostExecute(MainActivity.java:157)
at com.xxxx.weatherviewer.MainActivity$GetWeatherTask.onPostExecute(MainActivity.java:106)
at android.os.AsyncTask.finish(AsyncTask.java:755)
at android.os.AsyncTask.access$900(AsyncTask.java:192)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:772)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
I believe there might be an issue with the line listed below:
JSONArray list = forecast.getJSONArray("list");
However, I am unsure of how to start....can someone please help me?
A simple fix could be to turn your catch block from:
catch (JSONException e) {
e.printStackTrace();
}
into:
catch (Exception e) {
e.printStackTrace();
}
This catches your NPE, but do note that, if you have an API for this the "list" value could be empty or having a null value in that case you can always have a checker before doing the operation on JSONArray list variable. So for example before doing this:
JSONObject day = list.getJSONObject(i);
you can surround it with:
if(forecast.has("list")) {
JSONObject day = list.getJSONObject(i);
// Same goes for day etc...
}
This ensures that it should check if the object exists in the first place before processing it to avoid NPE.

Getting force close when trying to parse JSON Object Android

I have created REST web service using jersey which returns JSON response. JSON response returned by web service is as follow-
{
"Disease": "Bacterial_blight",
"Control": "Foliar sprays of streptocycline sulphate # 0.5 gm/land copper-oxychlode # 3 g / l of water as and when symptoms seen."
}
I have made Android app activity for demo purpose which contains one radio button, one Edit text box and one Button to submit the parameters to REST web service. But Problem is I'm getting force close when I try to click on Submit Button.
This is the actual android activity class code-
package com.doitgeek.agroadvisorysystem;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
public class DiseaseResultActivity extends AppCompatActivity {
public TextView diseaseTV;
public TextView controlMechanismTV;
public EditText etSymptom;
public RadioButton rbL;
public Button btnSubmit;
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_disease_result);
diseaseTV = (TextView)findViewById(R.id.diseaseTV);
controlMechanismTV = (TextView)findViewById(R.id.controlMechanismTV);
etSymptom = (EditText)findViewById(R.id.etSymptom);
rbL = (RadioButton)findViewById(R.id.rbL1);
btnSubmit = (Button)findViewById(R.id.btnSubmit);
}
public void onClickSubmit(View view) {
RequestParams params = new RequestParams();
String affectedPart = rbL.getText().toString();
String symptom = etSymptom.getText().toString();
params.put("affectedPart", affectedPart);
params.put("symptom", symptom);
invokeWS(params);
}
/* Invocation of RESTful WS */
public void invokeWS(RequestParams params) {
dialog.show();
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://192.168.0.100:8080/AgroAdvisorySystem/webapi/disease_prediction/result", params, new AsyncHttpResponseHandler(){
#Override
public void onSuccess(String response) {
dialog.hide();
try {
JSONObject obj = (JSONObject)new JSONTokener(response.toString()).nextValue();
JSONObject obj2 = obj.getJSONObject("Disease");
String disease = obj2.toString();
/*JSONObject obj = new JSONObject(response);
String disease = obj.getJSONObject("Disease").toString();*/
diseaseTV.setText(disease);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error Occurred [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
dialog.hide();
if(statusCode == 404) {
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
} else if(statusCode == 500) {
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unexpected Error occurred! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
}
}
});
}
}
I didn't find working solution till now that is why I am posting this as question.
So, what`s the Exception record?
It seems that the problem is in:
JSONObject obj2 = obj.getJSONObject("Disease");
where the item Disease is no longer a JSONObject.
Try obj.getSyting("Disease")

Error parsing dataorg.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

I work in a android app which should show the details of a virtual database(WAMPSERVER i use) and make new documents. When i push the button of show details the app displays the above error.The following is the allproductsactivity.java file.I have see and other similar post but i can't understand and solve my problem. I put x.x.x.x:80 on IP address for security reasons.
AllProductsActivity.java
package com.panos.appphpconnect;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class AllProductsActivity extends ListActivity {
private ProgressDialog pDialog;
JSONParser jParser=new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://x.x.x.x:80/connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CLASSES = "classes";
private static final String TAG_PID = "_id";
private static final String TAG_NAME = "username";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.allproducts);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String _id = ((ListView) view.findViewById(R.id.id)).getAdapter().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, _id);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(pDialog!=null && pDialog.isShowing()){
pDialog.cancel();
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON response
Log.d("All products:",json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_CLASSES);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.id, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
The code of get_all_products.php is the following
<?php
/*
* Following code will list all the products
*/
// array for json response
$response = array();
// include db connect class
require("db_connect.php");
// connecting to db
$db = new DB_CONNECT();
// get all products from classes table
$result = mysql_query("SELECT *FROM classes") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result)>0) {
// looping through all results
// products node
$response["classes"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$classes = array();
$classes["_id"] = $row["_id"];
$classes["username"] = $row["username"];
$classes["password"] = $row["password"];
// push single product into final response array
array_push($response["classes"], $classes);
}
// success
$response["success"] = 1;
// echoing panos response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No submissions found";
// echo no users json
echo json_encode($response);
}
?>
Also when i run the file get_all_products.php on my browser displays me the error " Parse error: syntax error, unexpected T_STRING, expecting T_FUNCTION in C:\wamp\www\connect\db_connect.php on line 6" but i don't understand which is line 6 and what is the error.The code of db_connect.php file is the below.
<?php
//A class file to connect to database
class DB_CONNECT{
function_constructor(){
$db = new DB_CONNECT();
//connecting to database
$this->connect();
}
function_destruct(){
//closing db connection
$this->close();
}
//Function to connect with database
function connect(){
//import database connection variables
require_once_DIR_ . '/db_config.php';
//connecting to mysql db
$con=mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD) or die(mysql_error());
//selecting database
$db=mysql_select_db(DB_DATABASE) or die(mysql_error());
//returning connrction cursor
return $con;
}
//function close to db connection
function close(){
//closing db connection
mysql_close();
}
}
?>
That's all errors of logocat
E/JSON Parser(2234): Error parsing dataorg.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
W/dalvikvm(2234): threadid=10: thread exiting with uncaught exception (group=0xb4e1e908)
E/AndroidRuntime(2234): FATAL EXCEPTION: AsyncTask #1
E/AndroidRuntime(2234): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime(2234): at android.os.AsyncTask$3.done(AsyncTask.java:299)
E/AndroidRuntime(2234): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
E/AndroidRuntime(2234): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
E/AndroidRuntime(2234): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
E/AndroidRuntime(2234): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
E/AndroidRuntime(2234): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
E/AndroidRuntime(2234): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
E/AndroidRuntime(2234): at java.lang.Thread.run(Thread.java:856)
E/AndroidRuntime(2234): Caused by: java.lang.NullPointerException
E/AndroidRuntime(2234): at com.panos.appphpconnect.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:141)
E/AndroidRuntime(2234): at com.panos.appphpconnect.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:1)
E/AndroidRuntime(2234): at android.os.AsyncTask$2.call(AsyncTask.java:287)
E/AndroidRuntime(2234): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
E/AndroidRuntime(2234): ... 4 more
SELECT *FROM classes is invalid syntax and when you query you should pass the connection to mysql_query
$result = mysql_query("SELECT * FROM classes", $db) or die(mysql_error());
And forget about android now, get this to work in your browser then you can worry about parsing it in your app.

how do i send parameters using my android app to a remote server using JSON. the code is given below

i am using a reference code for testing ,but when i run the app and click the submit button it shows "Unfortunately your app has Stopped".
Here is my java.class
package com.internship.mtslogin;
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.os.AsyncTask;
import android.os.Bundle;
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 fpasswd extends Activity implements OnClickListener{
private EditText email ;
private Button msubmit;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script
//localhost :
//testing on your device
//put your local ip instead, on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
private static final String LOGIN_URL ="http://xxx.xxx.x.x:1234/webservice/register.php";
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/register.php";
//ids
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_forgot_passwd);
email = (EditText)findViewById(R.id.email);
msubmit = (Button)findViewById(R.id.submit);
msubmit.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(fpasswd.this);
pDialog.setMessage("Please wait, Registering");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String emailid = email.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", emailid));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// full json response
Log.d("Login attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* 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(fpasswd.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
But when i run it in a localhost it works fine.
the parameters to be send is only "email".
and url in which i am doing is real server.
i have removed the real url and put a dummy url for string passing.
Can anyone tell me what is going wrong?
here is the logcat details.
FATAL EXCEPTION: AsyncTask #3
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
The answer is in the error message. You are missing INTERNET permission. Add to your manifest:
<uses-permission android:name="android.permission.INTERNET"/>
well it looks like you dont have access to the internet.
Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
Add this line to the AndroidMainfest.xml to enable the Internet access.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Updating mySQL database

When updating values into database, instead of updating 1 row each time(which is what we wanted), it update the whole database column.
Here are my codes:
Java code:
private Dialog alertDialog() { final AlertDialog.Builder
alertDialog = new AlertDialog.Builder(NotificationActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Confirmation...");
// Setting Dialog Message
alertDialog.setMessage("Do you want to accept this job?");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.ic_dialog_alert);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "Accept", Toast.LENGTH_SHORT).show();
// Return Result from alertdialog to database
result = "accepted";
System.out.println("The result is "+ result);
new UpdateActivity().execute();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "Reject", Toast.LENGTH_SHORT).show();
dialog.cancel();
// Return Result from alertdialog to database
result = "rejected";
System.out.println("The result is "+ result);
new UpdateActivity().execute();
}
});
return alertDialog.show(); }
/** * Background Async Task to update database * */ class
UpdateActivity extends AsyncTask {
/** * Before starting background thread Show Progress Dialog * */
#Override protected void onPreExecute() { super.onPreExecute();
pDialog = new ProgressDialog(NotificationActivity.this);
pDialog.setMessage("Sending ...");
pDialog.setIndeterminate(false); pDialog.setCancelable(true);
pDialog.show(); }
/** * Saving product * */ protected String
doInBackground(String... args) {
System.out.println("Sending...");
// getting updated data from dialog String confirmation =
result.toString();
System.out.println("Result to string..." + confirmation );
// Building Parameters List<NameValuePair> params = new
ArrayList(); params.add(new BasicNameValuePair(TAG_ID,
uid)); params.add(new BasicNameValuePair(TAG_RESULT, confirmation));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(UPDATE_URL,
"POST", params);
System.out.println("Json parsing...");
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
System.out.println("Checking...");
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), JobsAcceptedActivity.class);
startActivity(i);
//Toast.makeText(getApplicationContext(), "Update successfully...", Toast.LENGTH_SHORT).show();
System.out.println("Successfully updated...");
// closing this screen
finish();
} else {
// failed to create product
//Toast.makeText(getApplicationContext(), "Update unsucessfully...", Toast.LENGTH_SHORT).show();
System.out.println("Update unsuccessfully...");
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Done!");
return null; }
/**
* After completing background task Dismiss the progress dialog
* **/ protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss(); }
} }
PHP code:
$response = array(); // check for required fields if
(isset($_POST['UID']) && isset($_POST['accept'])) {
$UID = $_POST['UID'];
$accept = $_POST['accept'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql update row with matched pid
$result = mysql_query("UPDATE notification SET accept = '$accept' WHERE UID = $UID");
// check if column inserted or not
if ($result) {
// successfully updated
$response["success"] = 1;
$response["message"] = "Notification successfully updated.";
// echoing JSON response
echo json_encode($response);
} else {
} } else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
Q: When updating values into database, instead of updating 1 row each time(which is what we wanted), it update the whole database column.
A: It sounds like you probably want a more restrictive "where" clause on your update :)
This is your one ==> $result = mysql_query("UPDATE notification SET accept = '$accept' WHERE UID = $UID");
My Suggession ==> $result = mysql_query("UPDATE notification SET accept = '$accept' WHERE UID = '$UID'"); or
$queryString= "UPDATE notification SET accept = ".$accept." WHERE UID =".$UID;
$result = mysql_query($queryString);

Categories

Resources