Database cannot be connected - java

I m trying to create an application using eclipse. in the user-register page , after I entered all the required data, and click the submit button, the message " Unfortunately, your eclipse has been stopped". what does this message means and how to solve it?
public class UserRegister extends Activity {
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputUsername;
EditText inputEmail;
EditText inputPassword;
RadioButton button1;
RadioButton button2;
Button button3;
int success = 0;
// url to create new product
private static String url_register_user = "http://192.168.1.100/MEMS/add_user.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_register);
// Edit Text
inputName = (EditText) findViewById(R.id.nameTextBox);
inputUsername = (EditText) findViewById(R.id.usernameTextBox);
inputEmail = (EditText) findViewById(R.id.emailTextBox);
inputPassword = (EditText) findViewById(R.id.pwTextBox);
// Create button
//RadioButton button1 = (RadioButton) findViewById(R.id.studButton);
// RadioButton button2 = (RadioButton) findViewById(R.id.shopownerButton);
Button button3 = (Button) findViewById(R.id.regSubmitButton);
// button click event
button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputName.getText().toString();
String username = inputUsername.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
if(name.contentEquals("")||username.contentEquals("")||email.contentEquals("")||password.contentEquals(""))
{
AlertDialog.Builder builder = new AlertDialog.Builder(UserRegister.this);
// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage(R.string.nullAlert)
.setTitle(R.string.alertTitle);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
}
});
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.show();
}
else
{
new RegisterNewUser().execute();
}
}
});
}
class RegisterNewUser extends AsyncTask<String, String, String>{
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String username = inputUsername.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_register_user,
"GET", params);
// check log cat for response
Log.d("Send Notification", json.toString());
try
{
int success = json.getInt(TAG_SUCCESS);
if (success == 1)
{
// successfully created product
Intent i = new Intent(getApplicationContext(), StudentLogin.class);
startActivity(i);
finish();
}
else
{
// failed to register
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
}
My php file:
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for required fields
if (isset($_GET['name']) && isset($_GET['username']) && isset($_GET['email']) && isset($_GET['password'])) {
$name = $_GET['name'];
$username = $_GET['username'];
$email = $_GET['email'];
$password = $_GET['password'];
// mysql inserting a new row
$result = mysql_query("INSERT INTO register(name, username, email, password) VALUES('$name', '$username', '$email', '$password')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "You are successfully registered to MEMS.";
// echoing JSON response
echo json_encode($response);
}
else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>

Change the comparision method to equals() instead of contentEquals() in your code
as The String#equals() not only compares the String's contents, but also checks if the other object is also an instance of a String. The String#contentEquals() methods only compares the contents (the character sequence) and does not check if the other object is also an instance of String. It can be anything as long as it is an implementation of CharSequence or an instance of StringBuffer.
So change your code as like this
if(name.equals("")||username.equals("")||email.equals("")||password.equals(""))
{
....
}

Related

Can't insert data into database in android studio

Let me explain it better. i have made an app which has 3 fields. I want to insert these three fields into database. I'm getting 'data successfully inserted' message in toast but values are not getting inserted in database. Even i don't have any errors.. Thanku!
My php file:
<?php
//Define your host here.
$hostname = "localhost";
//Define your database username here.
$username = "root";
//Define your database password here.
$password = "root";
//Define your database name here.
$dbname = "SCPL";
$con = mysqli_connect($hostname,$username,$password,$dbname);
$name = $_POST['name'];
$email = $_POST['email'];
$website = $_POST['website'];
$Sql_Query = "insert into scpl (name,email,website) values ('$name','$email','$website')";
if(mysqli_query($con,$Sql_Query)){
echo 'Data Inserted Successfully';
}
else{
echo 'Try Again';
}
mysqli_close($con);
?>
This is my mainactivity.java class:
public class MainActivity extends Activity {
EditText editTextName, editTextEmail, editTextWebsite;
String GetName, GetEmail, GetWebsite;
Button buttonSubmit ;
String DataParseUrl = "http://192.168.2.6/androids/insert.php";
//String HttpURL = "http://192.168.2.26/Android_php/gps_tracker/insert.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextName = (EditText)findViewById(R.id.editText1);
editTextEmail = (EditText)findViewById(R.id.editText2);
editTextWebsite = (EditText)findViewById(R.id.editText3);
buttonSubmit = (Button)findViewById(R.id.button1);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
GetDataFromEditText();
SendDataToServer(GetName, GetEmail, GetWebsite);
}
});
}
public void GetDataFromEditText(){
GetName = editTextName.getText().toString();
GetEmail = editTextEmail.getText().toString();
GetWebsite = editTextWebsite.getText().toString();
}
public void SendDataToServer(final String name, final String email, final String website){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String QuickName = name ;
String QuickEmail = email ;
String QuickWebsite = website;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", QuickName));
nameValuePairs.add(new BasicNameValuePair("email", QuickEmail));
nameValuePairs.add(new BasicNameValuePair("website", QuickWebsite));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(DataParseUrl);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(MainActivity.this, "Data Submit Successfully", Toast.LENGTH_LONG).show();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, email,website);
}
}
i haven't found any errors/mistakes, try changing your URL/ip address to:
Use 10.0.2.2 for default AVD and 10.0.3.2 for genymotion.
Try using $_REQUEST instead of $_POST and check the response from the server first before showing the success message in your onPostExecute function like #MJM suggested.
I had similar problems with my API and android app when I was sending the data as POST request, the only way to get the submitted data was with $_REQUEST

Search remote database Android app

I want to create an Android app to be a search engine that can
search my remote database from server like MAMP,
list the search results and
select one of the results to view details.
I have already set up the database.
Search.java - the launch page that shows only a search bar, allows user to search:
public class Search extends Activity implements OnClickListener{
private EditText searchterm;
private Button mSubmit;
private SharedPreferences preferences;
private String preFileName="searchrequest"; //this is the Preference file Name
private String prefKey="searchterm"; //Key to store the User Name
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script
//localhost :
private static final String SEARCH_URL = "http://xxx.xxx.x.xxx:8888/searchdb/search.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.search);
searchterm = (EditText)findViewById(R.id.searchterm);
mSubmit = (Button)findViewById(R.id.searchnow);
mSubmit.setOnClickListener(this);
preferences=getSharedPreferences(preFileName, MODE_PRIVATE);
if(!preferences.getString(prefKey, "not_set").equals("not_set")){
prefKey.setText(preferences.getString(preFileName, "not_set"));
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.searchnow:
new SearchQuery().execute();
break;
default:
break;
}
}
public class SearchQuery extends AsyncTask<String,String,String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Search.this);
pDialog.setMessage("Checking for records...");
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 searchquery = searchterm.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("searchquery", searchquery));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
SEARCH_URL, "POST", params);
// full json response
Log.d("Search attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Successful Search!", json.toString());
//need help on how to save search data
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("searchquery", searchquery);
editor.apply();
Intent i = new Intent(Search.this, Result.class);
startActivity(i);
return json.getString(TAG_MESSAGE);
}else{
Log.d("Invalid query. Please try again.", 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(Search.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
Search.php:
<?php
# $db = new mysqli('localhost','username','password','db');
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database.
Please try again later.';
exit;
}
if (!empty($_POST)) {
$query_params = array(
$term = $_POST['searchquery']
);
$words = explode(" ", trim($term));
$termArray = array();
foreach($words as $word){
if(!empty($word)){
$termArray[] = "+$word";
}
}
$searchinput = implode(" ", $termArray);
$query = "SELECT *
FROM repairsvc
WHERE MATCH(title,address,cat,brand,company)
AGAINST ('".$searchinput."' IN BOOLEAN MODE)
ORDER BY title ASC";
try {
$result = $db->query($query);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
//This will be the variable to determine whether or not the user's information is correct.
//we initialize it as false.
$num_results = $result->num_rows;
if ($num_results == 0)
{
$search_ok = false;
}
else
{$search_ok = true;}
if ($search_ok) {
$response["success"] = 1;
$response["message"] = "Search Successful!";
$response["records"] = array();
$records = array();
while ($row = $result->fetch_assoc()) {
$records[] = array('title'=>$row["title"], 'address'=>$row["address"],
'company'=>$row["company"], 'id'=>$row["id"], 'brand'=>$row["brand"]); // push into the array
}
var_dump($records);
// foreach ($records as $row) {
// echo "Outlet: ", $row['title'], "; Address: ", $row['address'];
// }
//update our repsonse JSON data
array_push($response["records"], $records);
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Invalid Search! Please try again.";
die(json_encode($response));
}
} else {
?>
<h1>Search</h1>
<form name="form1" action="search.php" method="post">
Enter Search:<br />
<input type="text" name="searchquery" id="searchquery" placeholder="Search a repair service"/>
<br /><br />
<input type="submit" value="Search Now" name="completedsearch" />
</form>
<?php
}
?>
Problems:
How to save the search results from Search.java and let another activity Result.java to list results?
Save this from the php in first activity:
while ($row = $result->fetch_assoc()) {
$records[] = array('title'=>$row["title"], 'address'=>$row["address"],
'company'=>$row["company"], 'id'=>$row["id"], 'brand'=>$row["brand"]); // push into the array
}
//update our repsonse JSON data
array_push($response["records"], $records);
echo json_encode($response);
and put as listview in second activity (Result.java)??
Result.java --> select one of the results in list view, how to get details by searching database by posting id of the item?
I solved my question by putting this within Search.java to test whether can search:
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String searchquery = searchterm.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("searchquery", searchquery));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
SEARCH_URL, "POST", params);
// full json response
Log.d("Search attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Successful Search!", json.toString());
//save search data
mCommentList = new ArrayList<HashMap<String, String>>();
mComments = json.getJSONArray(TAG_POSTS);
// JSONArray mComments = new JSONArray(TAG_POSTS);
// looping through all posts according to the json object returned
for (int i = 0; i < mComments.length(); i++) {
JSONArray innerArray = mComments.optJSONArray(i);
for (int j = 0; j < innerArray.length(); j++) {
JSONObject c = innerArray.getJSONObject(j);
//gets the content of each tag
String title = c.getString(TAG_TITLE);
String address = c.getString(TAG_ADDRESS);
String brand = c.getString(TAG_BRAND);
String company = c.getString(TAG_COMPANY);
String id = c.getString(TAG_ID);
//so our JSON data is up to date same with our array list
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_ADDRESS, address);
map.put(TAG_BRAND, brand);
map.put(TAG_COMPANY, company);
map.put(TAG_ID, id);
mCommentList.add(map);
}
}
Intent r = new Intent(Search.this, Results.class);
//either
//r.putExtra("arraylist", mCommentList);
// startActivityForResult(r, 5000);
//or
r.putExtra("searchquery", searchquery);
startActivity(r);
return json.getString(TAG_MESSAGE);
}else{
Log.d("Invalid Search!", json.toString());
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Then in Results.java:
public void updateJSONdata() {
Bundle b = getIntent().getExtras();
String searchquery = b.getString("searchquery");
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("searchquery", searchquery));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
SEARCH_URL, "POST", params);
// full json response
Log.d("Search attempt", json.toString());
try {
mResultList = new ArrayList<HashMap<String, String>>();
mResults = json.getJSONArray(TAG_POSTS);
// JSONArray mComments = new JSONArray(TAG_POSTS);
// looping through all posts according to the json object returned
for (int i = 0; i < mResults.length(); i++) {
JSONArray innerArray = mResults.optJSONArray(i);
for (int j = 0; j < innerArray.length(); j++) {
JSONObject c = innerArray.getJSONObject(j);
//gets the content of each tag
String title = c.getString(TAG_TITLE);
String address = c.getString(TAG_ADDRESS);
String brand = c.getString(TAG_BRAND);
String company = c.getString(TAG_COMPANY);
String id = c.getString(TAG_ID);
//so our JSON data is up to date same with our array list
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_ADDRESS, address);
map.put(TAG_BRAND, brand);
map.put(TAG_COMPANY, company);
map.put(TAG_ID, id);
mResultList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into our listview
*/
private void updateList() {
//if you choose the other method
// final ArrayList<HashMap<String, String>> mResultList = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("arraylist");
// System.out.println("...serialized data.."+mResultList);
Bundle b = getIntent().getExtras();
final String searchquery = b.getString("searchquery");
ListAdapter adapter = new SimpleAdapter(this, mResultList,
R.layout.single_result, new String[]{TAG_TITLE, TAG_ADDRESS, TAG_BRAND,
TAG_COMPANY, TAG_ID}, new int[]{R.id.outlet, R.id.address, R.id.brand,
R.id.company});
setListAdapter(adapter);
listView.setSelector(R.drawable.listselector);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ListView Clicked item value
Map<String, String> map = (Map<String, String>) mResultList.get(position);
String record_id = map.get(TAG_ID);
Intent r = new Intent(Results.this, Record.class);
r.putExtra("key", record_id);
r.putExtra("searchquery", searchquery);
startActivity(r);
}
}
);
}

NullPointerException android app

I already know what a nullpointerexception is, but Im not able to find it in my own code. I hope you guys can see it
here is the log:
12-04 06:21:36.866 1687-1687/com.example.thelegendaryturk.theneckoptimizer E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.thelegendaryturk.theneckoptimizer, PID: 1687
java.lang.NullPointerException
at com.example.thelegendaryturk.theneckoptimizer.RegisterActivity$1.onClick(RegisterActivity.java:63)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Here is the RegisterActivity.java(line 63 is highlighted with ***)
public class RegisterActivity extends Activity {
Button btnRegister;
Button btnLinkToLogin;
EditText inputFullName;
EditText inputEmail;
EditText inputPassword;
TextView registerErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.registerName);
inputEmail = (EditText) findViewById(R.id.registerEmail);
inputPassword = (EditText) findViewById(R.id.registerPassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
// check for login response
try {
*** if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in registration
registerErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
// Close Registration View
finish();
}
});
}
}
Here is the UserFunction.java:
public class UserFunctions {
public JSONParser jsonParser;
private static String loginURL = "http://10.0.2.2/android_login_api/";
private static String registerURL = "http://10.0.2.2/android_login_api/";
private static String login_tag = "login";
private static String register_tag = "register";
// constructor
public UserFunctions(){
jsonParser = new JSONParser();
}
/**
* function make Login Request
* #param email
* #param password
* */
public JSONObject loginUser(String email, String password){
// Building Parameters
JSONObject json;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
json = jsonParser.getJSONFromUrl(loginURL, params);
// return json
// Log.e("JSON", json.toString());
return json;
}
/**
* function make Login Request
* #param name
* #param email
* #param password
* */
public JSONObject registerUser(String name, String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
// getting JSON Object
JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
// return json
return json;
}
/**
* Function get Login status
* */
public boolean isUserLoggedIn(Context context){
DatabaseHandler db = new DatabaseHandler(context);
int count = db.getRowCount();
if(count > 0){
// user logged in
return true;
}
return false;
}
/**
* Function to logout user
* Reset Database
* */
public boolean logoutUser(Context context){
DatabaseHandler db = new DatabaseHandler(context);
db.resetTables();
return true;
}
}
I think there is a simple solution but I am wasting my time for more than two hours now. Any help is welcome
First check json then check KEY_SUCCESS :
if (json!=null && json.getString(KEY_SUCCESS) != null) {
your problem is in either :
JSONObject json = userFunction.registerUser(name, email, password);
OR:
json.getString(KEY_SUCCESS)
even if you don't get the corresponding JSONObject from the userFunction or the String called KEY_SUCCESS is referenced to a null value.
I guess your problem is in Userfunction.registerUser()
json = jsonParser.getJSONFromUrl(loginURL, params);
step in here at debugging or check by code if json == null
if(json == null)
system.out.println("Error json object == null");
i think you really should find out why the jsonParser returns null at this point. Perhaps der url is not available?

Error Parsing data org.json.JSONException: Value 0 of type java.lang.integer cannot be converted to JSONObject

I'm trying to create a login page for my app using JSONParser, but everytime I click the login button, the error just keep coming on my username edittextbox "Java.lang.NullPointerException"
Here's my login.java:
public class login extends Activity{
private static final String loginurl = "http://10.0.2.2/koperasidb/login.php";
EditText kode,pw;
TextView error;
Button login;
String i;
private static final String TAG_SUCCESS = "success";
private Session session;
JSONParser1 jsonParser = new JSONParser1();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
session = new Session(this);
kode = (EditText) findViewById(R.id.kode);
pw = (EditText) findViewById (R.id.password);
login = (Button) findViewById (R.id.login);
error = (TextView) findViewById (R.id.error);
login.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("kode", kode.getText().toString()));
postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));
int success;
try {
JSONObject json = jsonParser.makeHttpRequest(loginurl, "GET", postParameters);
success = json.getInt(TAG_SUCCESS);
if (success ==1){
error.setText("Correct Username or Password");
session.setkdanggota(kode.getText().toString());
berhasil(v);
}
else {
error.setText("Sorry!! Wrong Username or Password Entered");
}
}
catch (Exception e) {
kode.setText(e.toString());
}
}
});
//Toast.makeText(this,"berhasil",3000).show();
}
public void berhasil (View theButton)
{
Intent s = new Intent (this, Home.class);
startActivity(s);
}
}
And here's my login.php:
<?php
include ("koneksi.php");
$kd=$_POST['kode'];
$pw=$_POST['password'];
$query = "SELECT * FROM anggota_baru WHERE kd_anggota = '$kd' AND no_identitas ='$pw'";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
if (mysql_num_rows($result) == 1){
echo 1;
$response["success"] = 1;
}
else {
// print status message
echo 0;
$response["success"] = 0;
}
?>
try
if (mysql_num_rows($result) == 1){
echo "{\"TAG_SUCCESS\":1}";
}else {
echo "{\"TAG_SUCCESS\":0}";
}
and in your activity use this line (put the double quotes)
success = json.getInt("TAG_SUCCESS");

Can't store data to the database

I'm working on an application that stores user inputs into the database table via PHP API but i get an error message from the PHP code to the LogCat. Any advice would be greatly appreciated.
D/Create Response(284): {"message":"Required field(s) is missing","success":0}
PHP API
<?php
// array for JSON response
$response = array();
// check for the fields
if (isset($_POST['title']) && isset($_POST['request_date']) && isset($_POST['reqEndDate']) && isset($_POST['reason']) && isset($_POST['requestor']) && isset($_POST['status']) && isset($_POST['submitDate']) && isset($_POST['explanation']) && isset($_POST['hours']) && isset($_POST['id'])) {
$title = $_POST["request_title"];
$date = $_POST["request_date"];
$eDate = $_POST["reqEndDate"];
$reason = $_POST["reason"];
$requestor = $_POST["requestor"];
$status = $_POST["status"];
$dateSubmitted = $_POST["submitDate"];
$explanation = $_POST["explanation"];
$numhours = $_POST["hours"];
$id = $_POST['id'];
// mysql inserting a new row
$result = mysql_query("INSERT INTO requests(request_title, request_date, reqEndDate, reason, requestor, status, submitDate, explanation, hours, empid)
VALUES('$title', '$date', '$eDate', '$reason', '$requestor', '$status', '$dateSubmitted', '$explanation', '$numhours', '$id')");
?>
JAVA CLASS
// url to the PHP API to create new request
private static String url_create_request = "http://mywebsite.com/create_request.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_request);
// Edit Text
inputTitle = (EditText) findViewById(R.id.inputTitle);
inputSdate = (EditText) findViewById(R.id.inputSdate);
inputEdate = (EditText) findViewById(R.id.inputEdate);
inputHours = (EditText) findViewById(R.id.inputHours);
inputReason = (EditText) findViewById(R.id.inputReason);
inputExp = (EditText) findViewById(R.id.inputExp);
// Create button
Button btnCreateRequest = (Button) findViewById(R.id.btnCreateRequest);
// button click event
btnCreateRequest.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// creating new product in background thread
new CreateNewRequest().execute();
}
});
}
class CreateNewRequest extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewRequestActivity.this);
pDialog.setMessage("Creating Request..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating Request Required Fields
* */
protected String doInBackground(String... args) {
String title = inputTitle.getText().toString();
String date = inputSdate.getText().toString();
String eDate = inputEdate.getText().toString();
String hours = inputHours.getText().toString();
String reason = inputReason.getText().toString();
String explanation = inputExp.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("request_title", title));
params.add(new BasicNameValuePair("request_date", date));
params.add(new BasicNameValuePair("reqEndDate", eDate));
params.add(new BasicNameValuePair("hours", hours));
params.add(new BasicNameValuePair("reason", reason));
params.add(new BasicNameValuePair("explanation", explanation));
// getting JSON Object
// Note that create request url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_request,
"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 request
Intent i = new Intent(getApplicationContext(), AllRequestsActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create request
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
Just counting your DB columns: there appears to be 12 of them. You're only inserting into 11, and after process of elimination, it looks like you're leaving out "active," which, unless it has a default value or can be null, would throw a "Required field(s) is missing" error that you're getting when trying to insert into the DB.

Categories

Resources