Android - php mysql. no updated values - java

im new to android and php languages. I want to add point for students upon clicking a button in android. My database table is 'user' and my column that i want it to be updated is 'point'.
I tried to use this code for point.php that will be activate in onclick button in android.
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$point = $_POST['point_add'];
$myVar = $point;
var_dump($myVar);
$myVar= $myVar += 1;
var_dump($myVar);
//importing database connection script
require "init.php";
//Creating sql query
$sql = "UPDATE user SET point = '$point' WHERE id = $id;";
//Updating database table
if(mysqli_query($con,$sql)){
echo 'Data Updated Successfully';
}else{
echo 'Could Not Update Data Try Again';
}
//closing connection
mysqli_close($con);
}
?>
this is my init.php
<?php
error_reporting(0);
$db_name = "mymerit";
$mysql_user = "root";
$mysql_pass = "root";
$server_name = "localhost";
$con = mysqli_connect($server_name, $mysql_user, $mysql_pass, $db_name);
if(!$con){
echo '{"message":"Unable to connect to the database."}';
}
?>
and this is my point.java in android
public class Point extends Activity implements View.OnClickListener{
String Err;
TextView err;
Button badd;
Context ctx=this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.point);
badd = (Button) findViewById(R.id.point_add);
err = (TextView) findViewById(R.id.err);
Err = getIntent().getStringExtra("err");
badd.setOnClickListener(this);
err.setText(Err);
}
public void onClick(View v){
BackGround b = new BackGround();
Intent intent = new Intent(this, Thanks.class);
startActivity(intent);
}
class BackGround extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String point = params[0];
String data="";
int tmp;
try {
URL url = new URL("http://192.168.1.12/android/point.php");
String urlParams = "point="+point;
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(urlParams.getBytes());
os.flush();
os.close();
InputStream is = httpURLConnection.getInputStream();
while((tmp=is.read())!=-1){
data+= (char)tmp;
}
is.close();
httpURLConnection.disconnect();
return data;
} catch (MalformedURLException e) {
e.printStackTrace();
return "Exception: "+e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "Exception: "+e.getMessage();
}
}
#Override
protected void onPostExecute(String s) {
if(s.equals("")){
s="Data saved successfully.";
}
Toast.makeText(ctx, s, Toast.LENGTH_LONG).show();
}
}
}
There's no error and the android's working fine. but my point is not updated to 1. Is my code wrong somewhere?

Is the point.php the actual file? Because there is a lot wrong there. You defined the variable $sql 3 times, first two don't have any effect on the code. I assume it's a snipped because you used variables that haven't been defined in the files, could you please clean up point.php? If this is actually the entire file try removing that error_reporting(0) and work your way through the errors.

If i've understood properly, you want to add counter each click of button and push it into the database. So you could use sharedPref or simple do this, int counter =0,
OnClick of button counter += 1;
then you can push counter value in the database, Same you can try with string :)

Related

progress dialog keeps on spinning even after inserting data

I am just creating a simple signup module. I have written the following code it inserts data but the progress dialog keeps on spinning and it never stops but if I check my database the data is there inserted correctly. I am using volley framework. I am a beginner on Android volley please tell me where I am going wrong.
registration.java
public class registration extends AppCompatActivity {
EditText Name,Email,Username,Password;
ProgressDialog dialog;
ProgressBar progressBar;
String Reg_url="------";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
Name=(EditText)findViewById(R.id.nametext);
Email=(EditText)findViewById(R.id.email);
Username=(EditText)findViewById(R.id.Username);
Password=(EditText)findViewById(R.id.pass);
dialog=new ProgressDialog(this);
dialog.setTitle("Loading");
dialog.setMessage("Please Wait a Momment");
dialog.setCancelable(false);
}
public void SignUp(View view)
{
if(TextUtils.isEmpty(Name.getText().toString()))
{
Name.setError("At least 5 charachters");
}
else if(TextUtils.isEmpty(Email.getText().toString()))
{
Email.setError("Enter a Valid Email");
}
else if(TextUtils.isEmpty(Username.getText().toString()))
{
Username.setError("At least 5 charachters");
}
else if(TextUtils.isEmpty(Password.getText().toString()))
{
Password.setError("At least 5 charachters");
}
else
{
dialog.show();
StringRequest stringRequest=new StringRequest(Request.Method.POST, Reg_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray=new JSONArray(response);
JSONObject jsonObject=jsonArray.getJSONObject(0);
dialog.dismiss();
finish();
startActivity(new Intent(registration.this,MainActivity.class));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(registration.this,"Connection Failed",Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map=new HashMap<String, String>();
map.put("name",Name.getText().toString());
map.put("email",Email.getText().toString());
map.put("user_name",Username.getText().toString());
map.put("password",Password.getText().toString());
return map;
}
};
int socketTimeout= 30000;
RetryPolicy policy=new DefaultRetryPolicy(socketTimeout,DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
}
I have added user permission for internet in the manifest file.
I have volley framework dependency volley 1.1.0.
It shows the onerrorresponse correctly but in response if i apply a toast that won't show either but data is inserted.
My php code is:
<?php
require "connect.php";
$name = $_POST["name"];
$email =$_POST["email"];
$user_name =$_POST["user_name"];
$password =$_POST["password"];
$sql = "INSERT INTO `user_info`(`name`, `email`, `user_name`, `password`) VALUES ('$name','$email','$user_name','$password')";
$result = mysqli_query($con,$sql);
mysqli_close($con);
?>
Change your response block like this
#Override
public void onResponse(String response) {
Toast.makeText(registration.this,"Response :"+response,Toast.LENGTH_SHORT).show();
try {
JSONArray jsonArray=new JSONArray(response);
dialog.dismiss();
finish();
startActivity(new Intent(registration.this,MainActivity.class));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
EDIT : Configure your php code in such a way that it returns a response during a network call. And then parse the response in the app side. Currently your try block is not getting executed due to no response from backend(even if the backend query is executed)
PHP code
<?php
require "connect.php";
$name = $_POST["name"];
$email =$_POST["email"];
$user_name =$_POST["user_name"];
$password =$_POST["password"];
$sql = "INSERT INTO `user_info`(`name`, `email`, `user_name`, `password`) VALUES ('$name','$email','$user_name','$password')";
$result = mysqli_query($con,$sql);
$myArray = array();
if($result){
$myArray = array("status" => "success", 'code' => "200")
} else{
$myArray = array("status" => "failure", 'code' => "400")
}
echo json_encode($myArray);
mysqli_close($con);
?>
Your try/catch block is likely failing. Test to make sure this is the case by a) setting a breakpoint on the try/catch block and running it line by line through the debugger until you find which line is causing the error to be thrown, or b) adding a log statement to the catch block that includes e.getLocalizedMessage() so you can see the error output, or c) just putting dialog.dismiss() in the catch black and see if it goes away. If you get the error message and don't know what it means post it and we'll get to the bottom of it.

Android Account Manager and starting another activity on successful login

I'm currently developing my app and I created simple authentication process. When user give login and password it sends data to server and it checks MySql database. I want to store user credentials in safe place which we know is Account Manager. I cant figure out how it works and how to apply it into my code.
Many tutorials that I found are old like 2010 or older..
This code works fine but I need to add changes. Like if user is succesfully logged in I want to start activity which will redirect him to MainPanel.class activity. I've tried to put code like this to SingnInActivity but it says method startActivity is not recognizable. Any ideas how to make it work?
public void login(View view){
Intent intent = new Intent(this, loginActivity.class);
startActivity(intent);
}
Can anybody help me? I appreciate any help.
My loginActivity looks like this:
public class loginActivity extends Activity {
private EditText usernameField,passwordField;
private TextView status,role;
public String d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
usernameField = (EditText)findViewById(R.id.usernameField);
passwordField = (EditText)findViewById(R.id.passwordField);
status = (TextView)findViewById(R.id.status);
role = (TextView)findViewById(R.id.textView5);
}
public void loginPost(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
//there I use another activity to 'sign in'
new SignInActivity(this,status,role).execute(username,password);
}
}
This is SignInActivity
public class SignInActivity extends AsyncTask<String,Void,String>{
private TextView statusField,roleField;
private Context context;
String d;
public SignInActivity(Context context, TextView statusField, TextView roleField) {
this.context = context;
this.statusField = statusField;
this.roleField = roleField;
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link="http://myserver/index.php";
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter
(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
d=sb.toString();
return d;
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
protected void onPostExecute(String result){
if(result.equals("adminstrator")){
this.statusField.setText("Yes");
//if user is in my database it changes statusfield to 'yes'
}
else{
this.statusField.setText("No");
}
this.roleField.setText(result);
}
}
There is no method startActivity in AsyncTask. It is in Activity class. If you don't understand what Inheritance is - start with that link.
Change Context to Activity:
private Activity context;
public SignInActivity(Activity context, TextView statusField, TextView roleField) {
this.context = context;
this.statusField = statusField;
this.roleField = roleField;
}
Then use
Intent intent = new Intent(this, MainPanel.class);
context.startActivity(intent);
Using the AccountManager is, actually, pretty complicated. You really just cannot drop it into an existing workflow. You'll need an implementation of the AbstractAccountAuthenticator that can be bound by the Android framework. It will call your login activity as necessary.
There is a fairly understandable example in this app
... and, incidentally, a good description of how it all works in my book, Enterprise Android

How to start a new activity on android client when receive a message from server

I have problem with starting a new activity in android. I have looked through many other questions here, but I didn't find an answer. Here's the problem:
Four classes:
1. WelcomeActivity;
2. MainActivity;
3. PopUpActivity;
4. Client;
At the begining starts WelcomeActivity where you you type all needed credentials to connect to the server, after you clicked the button, string is sent to server. Server send validation string if everything is OK. If OK is received, then MainActivity is started. Users types different things in MainActivity, the presses another button, which send another string to the server. Server processes it (string) and send back a response, also a string. And here's the problem. When server send that last string to client I want to start PopUpActivity, where will be displayed this aprticualr string in TextView.
My code:
Client part (last else if):
public void run() throws Exception {
Socket client = new Socket(ip, port);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
out.println(welcomeActivity.getCredentials());
while (true) {
final String line = in.readLine();
if (line.equals("#GO#")) {
System.out.println("#GO#");
mainActivityIntent = new Intent(welcomeActivity,
MainActivity.class);
welcomeActivity.startActivity(mainActivityIntent);
} else if (line.equals("#CLOSE#")) {
client.close();
break;
} else if (line.startsWith("#RESULTS")) {
Intent i = new Intent(MainActivity.getContext(), PopUpActivity.class);
i.putExtra(line, line);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainActivity.getContext().startActivity(i);
}
}
}
WelcomeActivity:
public void onClick(View v) {
ip = ipText.getText().toString();
port = Integer.parseInt(portText.getText().toString());
login = loginText.getText().toString();
password = passwordText.getText().toString();
credentials = login + "#" + password + "#" + brand + "#" + device + "#"
+ hardware + "#" + manufacturer + "#" + product;
client = new Client(ip, port, this);
new Handler().start();
}
private class Handler extends Thread {
public void run() {
try {
client.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}
PopUpActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop_up);
closeButton = (Button) findViewById(R.id.closeButton);
testOutcome = (TextView) findViewById(R.id.textArea);
closeButton.setOnClickListener(this);
//
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
String value = extras.getString(Intent.EXTRA_TEXT);
if (value != null) {
testOutcome.setText(value);
}
}
PopUpActivity is started, but text is not displayed.
Before that I tried to use Context in MainActivity:
final static Context context;
....
public void onCreate() {
context = getBaseContext();
// or context = getApplicationContext();
....
}
...
public static Context getContext() {
return context;
}
And from clint tried to call:
MainActivity.getContext().getTextView().setText(line);
At the begining I tied to call a AlertDialog, but it also was bad, NullPointerException
The problem is with your intent calling, so you may write
i.putExtra("line",line); in your MainActivity
and you can retrieve it by
Intent intent = getIntent(); intent.getStringExtra("line"); in your PopUp Activity.

android Java - Textview not appending text when activity restarts

I've been trying to create a function in my app that consist in a bluetooth RFID scanner, it's paired to my device and I have it working and all.
I can receive the text and log it in the console, when I compile the activity, everything goes fine, the stick reads the code, and then appends the text into an EditText, but if I go back and enter the activity again, I can see the code in the log, but the text doesn't go to the Edittext.
I tried a lot of different approaches, but nothing seems to work :/
here's the code I have:
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> bondedSet = mBluetoothAdapter.getBondedDevices();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available.", Toast.LENGTH_LONG).show();
}
if (!mBluetoothAdapter.isEnabled()) {
Toast.makeText(this, "Please enable your BT and re-run this program.", Toast.LENGTH_LONG).show();
finish();
}
if (mBluetoothAdapter.isEnabled()) {
if(bondedSet.size() == 1){
for(BluetoothDevice device : bondedSet){
address = device.getAddress();
Log.d("bt:", address);
}
}
}
String address = "00:A0:96:2A:0A:1B";
out = (EditText) findViewById(R.id.output);
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Log.d(TAG, device.getName() + " connected");
myConnection = new ConnectThread(device);
myConnection.start();
}
private class ConnectThread extends Thread {
private final BluetoothSocket mySocket;
Message msg;
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.d(TAG, "CONNECTION IN THREAD DIDNT WORK");
}
mySocket = tmp;
}
Handler uiThreadHandler = new Handler() {
public void handleMessage(Message msg) {
out = (EditText) findViewById(R.id.output);
Object o = msg.obj;
out.append(o.toString().trim());
Log.d("handler", o.toString());
}
};
public void run() {
out = (EditText) findViewById(R.id.output);
Log.d(TAG, "STARTING TO CONNECT THE SOCKET");
setName("My Connection Thread");
InputStream inStream = null;
boolean run = false;
mBluetoothAdapter.cancelDiscovery();
try {
mySocket.connect();
run = true;
} catch (IOException e) {
Log.d(TAG, this.getName() + ": CONN DIDNT WORK, Try closing socket");
try {
mySocket.close();
Log.d(TAG, this.getName() + ": CLOSED SOCKET");
} catch (IOException e1) {
Log.d(TAG, this.getName() + ": COULD CLOSE SOCKET", e1);
this.destroy();
}
run = false;
}
synchronized (BluetoothActivity.this) {
myConnection = null;
}
byte[] buffer = new byte[1024];
int bytes;
// handle Connection
try {
inStream = mySocket.getInputStream();
while (run) {
try {
bytes = inStream.read(buffer);
readMessage = new String(buffer, 0, bytes);
msg = uiThreadHandler.obtainMessage();
msg.obj = readMessage;
uiThreadHandler.sendMessage(msg);
Log.d(TAG, "Received: " + readMessage);
} catch (IOException e3) {
Log.d(TAG, "disconnected");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
My guess is that this has something to do with the Thread itself. When you start your Activity for the first time, you also call .start() on the Thread, that would work fine.
The problem is when you leave your Activity and open it up again. In that case, one of onStop() or onPause() is called (depending on situation), and onRestart() or onResume() will be called afterwards respectively.
The trick comes now: Meanwhile all that process, your Thread is still running. As you show your code, it has not been stopped/paused, and keeps running all the time. So basically my tip is that there's something you do within your onCreate() method of your Activity that should also be done in your onPause() and onStop() events, and my another tip it's somewhere within your ConnectThread(BluetoothDevice device) method.
To know how to procceed, I'd firstly define both onStop() and onPause() methods within your Activity and see which is fired, log every attribute to see its value/state, and that way you'll be able to debug what is failing.
There's a diagram of the Activity lifecycle.
Problem was solved, the code works, and the TextView get the inputstream, the problem was when i left the activity, the thread continued to work, so far, no problem at all, after TONS of hours spent on this, i turn the TextView a static var and it worked :)
If anyone reads this, i hope it helps.

Java/Android App unexpectedly closing / POSTing to server

I have no errors or warnings in Eclipse and I'm completely new to Android Programming so I don't even know where to start with this.
My app is just a simple form that I need to post to a php script online.
Here's the bulk of my main Activity minus the imports.. I don't have it set up to do anything with return values or any of that, and TBH i don't even know what would happen if it did work other than the data would be in my DB.. but the PHP script is not even being called by my app at all.
Based on things I found in Google, I have tried
-Adding Support Libraries
-Changing the target sdk version from 19 to 18
Please, what am I doing wrong?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_apply);
subm = (Button) findViewById(R.id.button1);
fname = (EditText) findViewById(R.id.editText1);
lname = (EditText) findViewById(R.id.editText2);
addr = (EditText) findViewById(R.id.editText3);
city = (EditText) findViewById(R.id.editText4);
state = (EditText) findViewById(R.id.editText5);
zip = (EditText) findViewById(R.id.editText6);
phone = (EditText) findViewById(R.id.editText7);
dob = (EditText) findViewById(R.id.editText8);
email = (EditText) findViewById(R.id.editText9);
ssn = (EditText) findViewById(R.id.editText10);
subm.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
String httpsURL = "https://example.com/apis/submit_credit_application.php";
String query = "fname="+URLEncoder.encode(fname.getText().toString(),"UTF-8");
query += "&lname="+URLEncoder.encode(lname.getText().toString(),"UTF-8");
query += "&addr="+URLEncoder.encode(addr.getText().toString(),"UTF-8");
query += "&city="+URLEncoder.encode(city.getText().toString(),"UTF-8");
query += "&state="+URLEncoder.encode(state.getText().toString(),"UTF-8");
query += "&zip="+URLEncoder.encode(zip.getText().toString(),"UTF-8");
query += "&phone="+URLEncoder.encode(phone.getText().toString(),"UTF-8");
query += "&dob="+URLEncoder.encode(dob.getText().toString(),"UTF-8");
query += "&email="+URLEncoder.encode(email.getText().toString(),"UTF-8");
query += "&ssn="+URLEncoder.encode(ssn.getText().toString(),"UTF-8");
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", String.valueOf(query.length()));
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(query);
output.close();
}catch(IOException e){
Toast.makeText(
getApplicationContext(),
(CharSequence) e,
Toast.LENGTH_LONG
).show();
}
}
});
}
here's a Pastebin with my logcat
As your error says you can't run network tasks on the the main thread. AsyncTasks are good for running short tasks that you don't want to block the main thread with.
Link to google docs.
http://developer.android.com/reference/android/os/AsyncTask.html
// This class is just added somewhere in your main activity, like a function.
private class PostFormTask extends AsyncTask<String, Integer, Long> {
protected Long doInBackground(String... queryDetails) {
try{
String httpsURL = "https://example.com/apis/submit_credit_application.php";
String query = "fname="+URLEncoder.encode(queryDetails[0],"UTF-8");
query += "&lname="+URLEncoder.encode(queryDetails[1],"UTF-8");
query += "&addr="+URLEncoder.encode(queryDetails[2],"UTF-8");
// Keep adding to your query but instead of getting your details
// from the textview they are in the queryDetails array.
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", String.valueOf(query.length()));
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(query);
output.close();
}catch(IOException e){
Toast.makeText(
getApplicationContext(),
(CharSequence) e,
Toast.LENGTH_LONG
).show();
}
return false
}
protected void onPostExecute(Long result) {
}
}
Then on your onClick event just have.
new PostFormTask().execute(fname.getText().toString(),
lname.getText().toString() );
// just send your form details to your task here, you will want to add all your details
// from your above code.
Hope that helps.
Alright! since you want you two points. Here is a good tutorial where i call a json web service using AsyncTask in andorid. Basically AsyncTask creates a new thread where network operations can be conducted.

Categories