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.
Related
I have a weird problem with showing my custom alert dialog from inside my async task's post execute method. When the program is run, the progress dialog from my pre-execute is first of all dismissed in the post execute before I then display my custom alert dialog which displays parsed JSON data. But the custom alert dialog does not show up at all, after dismissing the progress dialog.
Please, can anyone help with possible reasons why that's happening? Here is the code from my post exec method.
#Override
protected void onPostExecute(String result) {
loginDialog.dismiss();
jsonstring = result;
try {
jsonObject = new JSONObject(jsonstring);
jsonArray = jsonObject.getJSONArray("server_response");
JSONObject JO = jsonArray.getJSONObject(0);
fname = JO.getString("firstname");
lname = JO.getString("lastname");
possessionqty = JO.getString("possessionQty");
email = JO.getString("email");
status = JO.getString("status");
mBuilder = new AlertDialog.Builder(activity);
mView = getLayoutInflater().inflate(R.layout.studentinfo_alertdialog, null);
studentIDheader = (TextView) mView.findViewById(R.id.textView3);
studentfullname = (EditText) mView.findViewById(R.id.editText);
studentpossessionqty = (EditText) mView.findViewById(R.id.editText2);
studentemail = (EditText) mView.findViewById(R.id.editText3);
studentstatus = (EditText) mView.findViewById(R.id.editText4);
studentIDheader.setText(validatedID);
studentfullname.setText("Full Name: " + fname + " " + lname);
studentpossessionqty.setText("Possession Qty: " + possessionqty);
studentemail.setText("Email: " + email);
studentstatus.setText("Status: " + status);
mBuilder.setCancelable(false);
mBuilder.setView(mView);
dialog = mBuilder.create();
dialog.show();
} catch (JSONException e) {
e.printStackTrace();
}
}
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 :)
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
I'm trying to make a register page for my android app.
I have managed to create a login page and I'm now trying to get the register page to work.
I've managed to get the data I'm sending via the register page into the database. I'm using a php script to transfer the data into my mysql database.
But every time I register, it sends the data and gives the echo back saying that the username/mail already exists.
It also shows this error in Java: Invalid use of SingleClientConnManager: connection still allocated.
I've been trying to fix this for hours but can't find anything that helps.
This is my database:
id - primary key AI
mail - unique
password
username - unique
This is my php script
<?php
$hostname_memolink = "localhost";
$database_memolink = "memolink";
$username_memolink = "android";
$password_memolink ="f3.W2TmM}8yO";
$memolink = mysql_connect($hostname_memolink, $username_memolink, $password_memolink) or trigger_error(mysql_error(), E_USER_ERROR);
mysql_select_db($database_memolink, $memolink);
$mail = $_POST['mail'];
$password = $_POST['password'];
$username = $_POST['username'];
if (trim($password) == "" or trim($username) == "" or trim($mail) == "")
{
echo "variables are null";
exit;
}
else
{
$resultUsername = mysql_query("SELECT * FROM tbl_user WHERE username='$username'");
$resultMail = mysql_query("SELECT * FROM tbl_user WHERE mail='$mail'");
$num_rows_username = mysql_num_rows($resultUsername);
$num_rows_mail = mysql_num_rows($resultMail);
if ($num_rows_username >= 1 && $num_rows_mail >= 1) {
echo "username or email already exists";
die();
}
else
{
mysql_query("INSERT INTO tbl_user (id, mail, password, username) VALUES('', '$mail', '$password', '$username')") or die(mysql_error());
echo "registration complete";
}
}
?>
This is my Java method which sends the data to my php file:
HttpPost httpPost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpClient;
List<NameValuePair> registerData;
public void register(){
try{
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://www.memo-link.be/php/register.php");
registerData = new ArrayList<NameValuePair>(2);
EditText mailBox = (EditText) findViewById(R.id.mail_box);
EditText userBox = (EditText) findViewById(R.id.username_box);
EditText passBox = (EditText) findViewById(R.id.password_box);
String mail = mailBox.getText().toString();
String username = userBox.getText().toString();
String password = passBox.getText().toString();
registerData.add(new BasicNameValuePair("mail", mail));
registerData.add(new BasicNameValuePair("username", username));
registerData.add(new BasicNameValuePair("password", password));
httpPost.setEntity(new UrlEncodedFormEntity(registerData));
response = httpClient.execute(httpPost); //send data to Internet
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpClient.execute(httpPost, responseHandler);
System.out.println("Response : " + response.toString());
if (response.equalsIgnoreCase("username or email already exists")){
runOnUiThread(new Runnable(){
public void run(){
dialog.dismiss();
}
});
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(250);
Toast toast = Toast.makeText(RegisterActivity.this, "Username already exists!", Toast.LENGTH_SHORT);
toast.show();
}else if(response.toString().equalsIgnoreCase("username or email already exists")){
runOnUiThread(new Runnable(){
public void run(){
dialog.dismiss();
}
});
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(250);
Toast toast = Toast.makeText(RegisterActivity.this, "Mail address already in use!", Toast.LENGTH_SHORT);
toast.show();
}else if(response.toString().equalsIgnoreCase("registration complete")){
runOnUiThread(new Runnable(){
public void run(){
Toast toast = Toast.makeText(RegisterActivity.this, "Registration Succesfull", Toast.LENGTH_SHORT);
toast.show();
}
});
startActivity(new Intent(RegisterActivity.this, DashboardActivity.class));
}
runOnUiThread(new Runnable(){
public void run(){
dialog.dismiss();
}
});
}catch (Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
Thanks in advance
Please see this, if this might help you. Let us know if you need more help.
Android: Invalid use of SingleClientConnManager: connection still allocated
Also, in your code, you are executing the query twice, which on the first time executes normally and as soon as it gets second query (as your data is already inserted), this satisfies the condition and prints the error message. Hope this will help.
I am trying to send 'id' from my fragment activity to an activity and parsing json data based on this 'id' field.
I am successfully sending data from fragment to TourDetail activity, but it is not parsing the json based on same 'id'. The code is not reaching second try block as I examined it using toasts.
Although the same activity(TourDetailActivity.java) is working fine when I pass 'id' from some other activity. Say, if I passed 'id' from jsonuseactivity.java, it is received successfully by TourDetailActivity.java and the respective json result is generated and the appropriate result is displayed.
But if the same 'id' is passed from the fragment activity, it is although receiving the 'id' but not generating the json and no required results based on json are being generated.
TourDetailActivity.java
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tour_detail);
Intent intent = getIntent();
String rcvid = intent.getStringExtra("id");
Toast.makeText(getApplicationContext(), rcvid, Toast.LENGTH_LONG).show();
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("tourid", rcvid));
String response = null;
// call executeHttpPost method passing necessary parameters
try {
Toast.makeText(getApplicationContext(), "in try block", Toast.LENGTH_LONG).show();
response = CustomHttpClient.executeHttpPost(
//"http://129.107.187.135/CSE5324/jsonscript.php", // your ip address if using localhost server
"http://www.futurolicht.com/jsontour.php", // in case of a remote server
postParameters);
String result = response.toString();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
//parse json data
try {
Toast.makeText(getApplicationContext(), "in 2nd try block", Toast.LENGTH_LONG).show();
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
tname = (TextView) findViewById(R.id.txt_tourtitle);
td = (TextView) findViewById(R.id.txt_day);
tn = (TextView) findViewById(R.id.txt_night);
tdest = (TextView) findViewById(R.id.txt_tourdetail_dest);
btn = (Button) findViewById(R.id.btn_tourdetail);
btn.setOnClickListener(this);
tname.setText(json_data.getString("tour_name"));
tn.setText(json_data.getString("nights"));
td.setText(json_data.getString("days"));
name = json_data.getString("tour_name");
n = json_data.getString("nights");
d = json_data.getString("days");
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
This is my Fragmentone.java's onCreate() method code:
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_one, null);
String fontPath = "fonts/ox.ttf";
b1 = (Button)root.findViewById(R.id.featured_btn1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String id = "34";
Intent intent = new Intent(getActivity(), TourDetailActivity.class);
intent.putExtra("id", id);
getActivity().startActivity(intent);
}
});
I didn't know what actually happened as above code seems okay to me. Instead of sending data, you can make the variable as Static and access that variable in other class like Fragmentone.id. This will definitely work.
Also did you try to catch that id in onStart() instead of onCreate() ? It is convenient to check if there are arguments passed to the fragment in startup