im doing a login register for my application and i have to integrate them together with microsoft azure. However, despite after following the tutorial given by microsoft azure, i still fail to insert my "string" into their database. There are also no error in the codes, hence i'm not very sure where is wrong. Below is my codes.
package mp.memberuse;
import java.net.MalformedURLException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import com.microsoft.windowsazure.mobileservices.*;
public class LoginRegister extends Activity {
Button btn1, btn2, btn3;
EditText tf1, tf2, tf3, tf4, tf5, tf6, tf7, tf8, tf9, tf10, tf11;
TextView tv1, tv2;
private MobileServiceClient mClient;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TabHost tabs = (TabHost) this.findViewById(R.id.lt2tabhost);
tabs.setup();
TabSpec ts1 = tabs.newTabSpec("Login");
ts1.setIndicator("Login");
ts1.setContent(R.id.c1);
tabs.addTab(ts1);
TabSpec ts2 = tabs.newTabSpec("Register");
ts2.setIndicator("Register");
ts2.setContent(R.id.c2);
tabs.addTab(ts2);
btn1 = (Button)findViewById(R.id.button1);
btn2 = (Button)findViewById(R.id.button2);
btn3 = (Button)findViewById(R.id.button3);
tf1=(EditText) findViewById(R.id.editText1);
tf2=(EditText) findViewById(R.id.editText2);
tf3=(EditText) findViewById(R.id.editText3);
tf4=(EditText) findViewById(R.id.editText4);
tf5=(EditText) findViewById(R.id.editText5);
tf6=(EditText) findViewById(R.id.editText6);
tf7=(EditText) findViewById(R.id.editText7);
tf8=(EditText) findViewById(R.id.editText8);
tf9=(EditText) findViewById(R.id.editText9);
tf10=(EditText) findViewById(R.id.editText10);
tv1=(TextView) findViewById(R.id.login);
tv2=(TextView) findViewById(R.id.register);
try {
MobileServiceClient mClient = new MobileServiceClient("https://testrun.azure-mobile.net/","FOJanABDYiJEVMHkCECAylrXJCnVwF77",this);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
btn1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
String username, password;
username = tf1.getText().toString();
password = tf2.getText().toString();
/**if(username.equals(sqlusername) && password.equals(sqlpassword))
{
SharedPreferences prefs = getSharedPreferences("myPreferences",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("fullname", fullname);
editor.commit();
Intent intent = new Intent(LoginRegister.this, SendMessage.class);
startActivity(intent);
}
else
{
tv1.setText("Invalid user");
} **/
}
}
);
btn2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
String username, password, cpassword, fullname, nric, address, phone, email;
username = tf3.getText().toString();
password = tf4.getText().toString();
cpassword = tf5.getText().toString();
fullname = tf6.getText().toString();
nric = tf7.getText().toString();
address = tf8.getText().toString();
phone = tf9.getText().toString();
email = tf10.getText().toString();
Members members = new Members();
members.username = username;
members.password = password;
members.fullname = fullname;
members.nric = nric;
members.address = address;
members.phone = phone;
members.email = email;
if(!password.equals(cpassword))
{
tv2.setText("Password & Confirm Password does not match.");
}
else if(username.equals("") || password.equals("") || cpassword.equals("") || fullname.equals("") || nric.equals("") || address.equals("") || phone.equals("") || email.equals(""))
{
tv2.setText("Do not leave any field empty.");
}
else
{
mClient.getTable(Members.class).insert(members, new TableOperationCallback<Members>()
{
public void onCompleted(Members entity, Exception exception, ServiceFilterResponse response)
{
if (exception == null)
{
tv2.setText("Register Complete.");
tf3.setText("");
tf4.setText("");
tf5.setText("");
tf6.setText("");
tf7.setText("");
tf8.setText("");
tf9.setText("");
tf10.setText("");
}
else
{
tv2.setText("Fail to register!");
}
}
});
tv2.setText("Register Complete.");
tf3.setText("");
tf4.setText("");
tf5.setText("");
tf6.setText("");
tf7.setText("");
tf8.setText("");
tf9.setText("");
tf10.setText("");
}
}
});
btn3.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
tf3.setText("");
tf4.setText("");
tf5.setText("");
tf6.setText("");
tf7.setText("");
tf8.setText("");
tf9.setText("");
tf10.setText("");
}
});
}
}
Here is an code snippet , hoping it will help you.
1)An function which carries the http get service
private String SendDataFromAndroidDevice() {
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet getMethod = new HttpGet("your url + data appended");
BufferedReader in = null;
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient
.execute(getMethod);
in = new BufferedReader(new InputStreamReader(httpResponse
.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
2) An Class which extends AsyncTask
private class HTTPdemo extends
AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... params) {
String result = SendDataFromAndroidDevice();
return result;
}
#Override
protected void onProgressUpdate(Void... values) {}
#Override
protected void onPostExecute(String result) {
if (result != null && !result.equals("")) {
try {
JSONObject resObject = new JSONObject(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
3) Inside your onCreate method
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView("your layout");
if ("check here where network/internet is avaliable") {
new HTTPdemo().execute("");
}
}
The code snippet provided by me works in the following way,
1)Android device send the URL+data to server
2)Server [Azure platform used] receive the data and gives an acknowledgement
Now the Code which should be written at client side (Android) is provided to you, the later part of receiving that data at server is
Server needs to receive the data
An webservice should be used to do that
Implement an webservice at server side
The webservice will be invoked whenever android will push the URL+data
Once you have the data ,manipulated it as you want
Related
Hey guys again with my question
So as in the title, my apps need data from another activity using sharedPreferenced
So far so good I got the data I store WHEN I click the button but when i tried to get the data on the onCreate it just crashing with this error code:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.test.aplikasirevisi, PID: 28272
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.aplikasirevisi/com.test.aplikasirevisi.Information}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.test.aplikasirevisi.Information.onCreate(Information.java:33)
at android.app.Activity.performCreate(Activity.java:7224)
at android.app.Activity.performCreate(Activity.java:7213)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2926)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
I/Process: Sending signal. PID: 28272 SIG: 9
It says it's null but when I click the button it's giving me the data though
Here is my code:
Information.Java
package com.test.aplikasirevisi;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.Nullable;
public class Information extends Activity {
SharedPreferences sharedpreferences;
TextView name;
TextView phonenum;
TextView highest;
TextView lowest;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
public static final String PhoneNum = "phonenumKey";
public static final String Highest = "highestKey";
public static final String Lowest = "lowestKey";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(PhoneNum)) {
phonenum.setText(sharedpreferences.getString(PhoneNum, ""));
}
if (sharedpreferences.contains(Highest)) {
highest.setText(sharedpreferences.getString(Highest, ""));
}
if (sharedpreferences.contains(Lowest)) {
lowest.setText(sharedpreferences.getString(Lowest, ""));
}
}
public void Save(View view) {
String n = name.getText().toString();
String p = phonenum.getText().toString();
String h = highest.getText().toString();
String l = lowest.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(PhoneNum, p);
editor.putString(Highest, h);
editor.putString(Lowest, l);
editor.commit();
}
public void clear(View view) {
name = (TextView) findViewById(R.id.etName);
phonenum = (TextView) findViewById(R.id.etPhoneNum);
highest = (TextView) findViewById(R.id.etHighest);
lowest = (TextView) findViewById(R.id.etLowest);
name.setText("");
phonenum.setText("");
highest.setText("");
lowest.setText("");
}
public void Get(View view) {
name = (TextView) findViewById(R.id.etName);
phonenum = (TextView) findViewById(R.id.etPhoneNum);
highest = (TextView) findViewById(R.id.etHighest);
lowest = (TextView) findViewById(R.id.etLowest);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(PhoneNum)) {
phonenum.setText(sharedpreferences.getString(PhoneNum, ""));
}
if (sharedpreferences.contains(Highest)) {
highest.setText(sharedpreferences.getString(Highest, ""));
}
if (sharedpreferences.contains(Lowest)) {
lowest.setText(sharedpreferences.getString(Lowest, ""));
}
}
}
MonitoringScreen.Java
package com.test.aplikasirevisi;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import static com.test.aplikasirevisi.Information.Highest;
import static com.test.aplikasirevisi.Information.Lowest;
import static com.test.aplikasirevisi.Information.mypreference;
public class MonitoringScreen extends Activity {
private static final String TAG = "BlueTest5-MainActivity";
private int mMaxChars = 50000;//Default
private UUID mDeviceUUID;
private BluetoothSocket mBTSocket;
private ReadInput mReadThread = null;
TextView highest;
TextView lowest;
private boolean mIsUserInitiatedDisconnect = false;
private TextView mTxtReceive;
private Button mBtnClearInput;
private Button mBtnGetBPM;
private ScrollView scrollView;
private CheckBox chkScroll;
private CheckBox chkReceiveText;
private boolean mIsBluetoothConnected = false;
private BluetoothDevice mDevice;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_monitoring_screen);
ActivityHelper.initialize(this);
Intent intent = getIntent();
Bundle b = intent.getExtras();
mDevice = b.getParcelable(MainActivity.DEVICE_EXTRA);
mDeviceUUID = UUID.fromString(b.getString(MainActivity.DEVICE_UUID));
mMaxChars = b.getInt(MainActivity.BUFFER_SIZE);
Log.d(TAG, "Ready");
mTxtReceive = (TextView) findViewById(R.id.txtReceive);
chkScroll = (CheckBox) findViewById(R.id.chkScroll);
chkReceiveText = (CheckBox) findViewById(R.id.chkReceiveText);
scrollView = (ScrollView) findViewById(R.id.viewScroll);
mBtnClearInput = (Button) findViewById(R.id.btnClearInput);
mBtnGetBPM = (Button) findViewById(R.id.mBtnGetBPM);
mTxtReceive.setMovementMethod(new ScrollingMovementMethod());
mBtnClearInput.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mTxtReceive.setText("");
}
});
mBtnGetBPM.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
highest = (TextView) findViewById(R.id.etHighest);
lowest = (TextView) findViewById(R.id.etLowest);
SharedPreferences sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Highest)) {
highest.setText(sharedpreferences.getString(Highest, ""));
}
if (sharedpreferences.contains(Lowest)) {
lowest.setText(sharedpreferences.getString(Lowest, ""));
}
}
});
}
private class ReadInput implements Runnable{
private boolean bStop = false;
private Thread t;
public ReadInput() {
t = new Thread(this, "Input Thread");
t.start();
}
public boolean isRunning() {
return t.isAlive();
}
#Override
public void run() {
InputStream inputStream;
try {
inputStream = mBTSocket.getInputStream();
while (!bStop) {
byte[] buffer = new byte[256];
if (inputStream.available() > 0) {
inputStream.read(buffer);
int i;
/*
* This is needed because new String(buffer) is taking the entire buffer i.e. 256 chars on Android 2.3.4 http://stackoverflow.com/a/8843462/1287554
*/
for (i = 0; i < buffer.length && buffer[i] != 0; i++) {
}
final String strInput = new String(buffer, 0, i);
String getHi = null;
SharedPreferences sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Highest)) {
highest.setText(sharedpreferences.getString(Highest, ""));
getHi=highest.getText().toString();
}
if (sharedpreferences.contains(Lowest)) {
lowest.setText(sharedpreferences.getString(Lowest, ""));
}
int hi = Integer.parseInt(getHi);
/*
* If checked then receive text, better design would probably be to stop thread if unchecked and free resources, but this is a quick fix
*/
if (chkReceiveText.isChecked()) {
mTxtReceive.post(new Runnable() {
#Override
public void run() {
int data = Integer.parseInt(strInput);
mTxtReceive.append(strInput);
int txtLength = mTxtReceive.getEditableText().length();
if(txtLength > mMaxChars){
mTxtReceive.getEditableText().delete(0, txtLength - mMaxChars);
Log.d(TAG, "text longer than allowed:" + mTxtReceive.getEditableText().delete(0, txtLength - mMaxChars));
Log.d(TAG, strInput);
if(data > hi){
Log.d(TAG, "Success");
}
}
if (chkScroll.isChecked()) { // Scroll only if this is checked
scrollView.post(new Runnable() { // Snippet from http://stackoverflow.com/a/4612082/1287554
#Override
public void run() {
scrollView.fullScroll(View.FOCUS_DOWN);
}
});
}
}
});
}
}
Thread.sleep(500);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stop() {
bStop = true;
}
}
private class DisConnectBT extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
if (mReadThread != null) {
mReadThread.stop();
while (mReadThread.isRunning())
; // Wait until it stops
mReadThread = null;
}
try {
mBTSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mIsBluetoothConnected = false;
if (mIsUserInitiatedDisconnect) {
finish();
}
}
}
private void msg(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
if (mBTSocket != null && mIsBluetoothConnected) {
new DisConnectBT().execute();
}
Log.d(TAG, "Paused");
super.onPause();
}
#Override
protected void onResume() {
if (mBTSocket == null || !mIsBluetoothConnected) {
new ConnectBT().execute();
}
Log.d(TAG, "Resumed");
super.onResume();
}
#Override
protected void onStop() {
Log.d(TAG, "Stopped");
super.onStop();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> {
private boolean mConnectSuccessful = true;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MonitoringScreen.this, "Hold on", "Connecting");// http://stackoverflow.com/a/11130220/1287554
}
#Override
protected Void doInBackground(Void... devices) {
try {
if (mBTSocket == null || !mIsBluetoothConnected) {
mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
mBTSocket.connect();
}
} catch (IOException e) {
// Unable to connect to device
e.printStackTrace();
mConnectSuccessful = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!mConnectSuccessful) {
Toast.makeText(getApplicationContext(), "Could not connect to device. Is it a Serial device? Also check if the UUID is correct in the settings", Toast.LENGTH_LONG).show();
finish();
} else {
msg("Connected to device");
mIsBluetoothConnected = true;
mReadThread = new ReadInput(); // Kick off input reader
}
progressDialog.dismiss();
}
}
}
As you can see I tried to automatically get the Highest bpm dan Lowest bpm but it spans the same error so I'm in a pickle now so if anyone can help with it dan fast I'll be grateful for that. And sorry for my English it's not my first language so I can't express it really well.
The TextView in your Information.Java are not assigned to anything within your onCreate method before you try calling the setText method. This is what the error is complaining about.
Your assignments are in the clear(View view) method for some reason.... they should be in the onCreate method.
i.e move
name = (TextView) findViewById(R.id.etName);
phonenum = (TextView) findViewById(R.id.etPhoneNum);
highest = (TextView) findViewById(R.id.etHighest);
lowest = (TextView) findViewById(R.id.etLowest);
out of the clear and get methods and into the onCreate method like:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information);
name = (TextView) findViewById(R.id.etName);
phonenum = (TextView) findViewById(R.id.etPhoneNum);
highest = (TextView) findViewById(R.id.etHighest);
lowest = (TextView) findViewById(R.id.etLowest);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(PhoneNum)) {
phonenum.setText(sharedpreferences.getString(PhoneNum, ""));
}
if (sharedpreferences.contains(Highest)) {
highest.setText(sharedpreferences.getString(Highest, ""));
}
if (sharedpreferences.contains(Lowest)) {
lowest.setText(sharedpreferences.getString(Lowest, ""));
}
}
I tried all i can find in previous similar posts but it didnt help. I get the error: "I/System.out: Error: org.json.JSONException: Value br of type java.lang.String cannot be converted to JSONObject"
Java Code:
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import
com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONException;
import org.json.JSONObject;
public class RegisterActivity extends AppCompatActivity {
private static final String KEY_STATUS = "status";
private static final String KEY_MESSAGE = "message";
private static final String KEY_FULL_NAME = "full_name";
private static final String KEY_USERNAME = "username";
private static final String KEY_PASSWORD = "password";
private static final String KEY_EMPTY = "";
private EditText etUsername;
private EditText etPassword;
private EditText etConfirmPassword;
private EditText etFullName;
private String username;
private String password;
private String confirmPassword;
private String fullName;
private ProgressDialog pDialog;
private String register_url = "http://10.0.2.2/user102/register.php";
private SessionHandler session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
session = new SessionHandler(getApplicationContext());
setContentView(R.layout.activity_register);
etUsername = findViewById(R.id.etUsername);
etPassword = findViewById(R.id.etPassword);
etConfirmPassword = findViewById(R.id.etConfirmPassword);
etFullName = findViewById(R.id.etFullName);
Button login = findViewById(R.id.btnRegisterLogin);
Button register = findViewById(R.id.btnRegister);
//Launch Login screen when Login Button is clicked
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(RegisterActivity.this, Login.class);
startActivity(i);
finish();
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Retrieve the data entered in the edit texts
username = etUsername.getText().toString().toLowerCase().trim();
password = etPassword.getText().toString().trim();
confirmPassword = etConfirmPassword.getText().toString().trim();
fullName = etFullName.getText().toString().trim();
if (validateInputs()) {
registerUser();
}
}
});
}
/**
* Display Progress bar while registering
*/
private void displayLoader() {
pDialog = new ProgressDialog(RegisterActivity.this);
pDialog.setMessage("Signing Up.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* Launch Dashboard Activity on Successful Sign Up
*/
private void loadDashboard() {
Intent i = new Intent(getApplicationContext(), DashboardActivity.class);
startActivity(i);
finish();
}
private void registerUser() {
displayLoader();
JSONObject request = new JSONObject();
try {
//Populate the request parameters
request.put(KEY_USERNAME, username);
request.put(KEY_PASSWORD, password);
request.put(KEY_FULL_NAME, fullName);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("JSON= "+ request.toString());
JsonObjectRequest jsArrayRequest = new JsonObjectRequest
(Request.Method.POST, register_url, request, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
try {
//Check if user got registered successfully
if (response.getInt(KEY_STATUS) == 0) {
//Set the user session
session.loginUser(username,fullName);
loadDashboard();
}else if(response.getInt(KEY_STATUS) == 1){
//Display error message if username is already existsing
etUsername.setError("Username already taken!");
etUsername.requestFocus();
}else{
Toast.makeText(getApplicationContext(),
response.getString(KEY_MESSAGE), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
System.out.println("Error: "+error.getMessage());
//Display error message whenever an error occurs
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
}
/**
* Validates inputs and shows error if any
* #return
*/
private boolean validateInputs() {
if (KEY_EMPTY.equals(fullName)) {
etFullName.setError("Full Name cannot be empty");
etFullName.requestFocus();
return false;
}
if (KEY_EMPTY.equals(username)) {
etUsername.setError("Username cannot be empty");
etUsername.requestFocus();
return false;
}
if (KEY_EMPTY.equals(password)) {
etPassword.setError("Password cannot be empty");
etPassword.requestFocus();
return false;
}
if (KEY_EMPTY.equals(confirmPassword)) {
etConfirmPassword.setError("Confirm Password cannot be empty");
etConfirmPassword.requestFocus();
return false;
}
if (!password.equals(confirmPassword)) {
etConfirmPassword.setError("Password and Confirm Password does not match");
etConfirmPassword.requestFocus();
return false;
}
return true;
}
Php Code:
<?php
$response = array();
include 'db/db_connect.php';
include 'db/functions.php';
//Get the input request parameters
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
//convert JSON into array
//Check for Mandatory parameters
if(isset($input['username']) &&
isset($input['password']) &&
isset($input['full_name'])){
$username = $input['username'];
$password = $input['password'];
$fullName = $input['full_name'];
//Check if user already exist
if(!userExists($username)){
//Get a unique Salt
$salt = getSalt();
//Generate a unique password Hash
$passwordHash = password_hash(concatPasswordWithSalt($password,$salt),PASSWORD_DEFAULT);
//Query to register new user
$insertQuery = "INSERT INTO user_data(username, full_name, password_hash, salt) VALUES (?,?,?,?)";
if($stmt = $con->prepare($insertQuery)){
$stmt->bind_param("ssss",$username,$fullName,$passwordHash,$salt);
$stmt->execute();
$response["status"] = 0;
$response["message"] = "User created";
$stmt->close();
}
}
else{
$response["status"] = 1;
$response["message"] = "User exists";
}
}
else{
$response["status"] = 2;
$response["message"] = "Missing
mandatory parameters";
}
echo json_encode($response);
?>
Does the register_url string cannot be converted? I am very new to this. Thank you
Try like this
try{
JSONArray parametersForPhp = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put(key,value);
jsonObject.put(key,value);
parametersForPhp.put(jsonObject);
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, httpurl, parametersForPhp,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG,response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
RequestQueueSingleton.getInstance(getApplicationContext()).addToRequestQueue(arrayRequest);
}catch(Exception e){
e.printStackTrace();
}
Currently I am working on developing an app through Android Studio and working on coding the login and registration capabilities. We send newly registered users' info to a MySQL database externally (i.e. not locally) through PHP, and also want to log registered users into the app. At the moment, the Android app is not sending the PHP file the information the user types into the text boxes. I put a tracer into the PHP file and it shows that the values are coming up null.
Here is my MainActivity.java:
package android.capstone.registerlogin;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import static android.capstone.registerlogin.R.id.etCreateAccEmail;
import static android.capstone.registerlogin.R.id.etCreateAccPassword;
import static android.capstone.registerlogin.R.id.etCreateAccUsername;
public class MainActivity extends Activity {
private EditText etUserName, etPassWord, etEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
etPassWord = (EditText) findViewById(etCreateAccPassword);
etUserName = (EditText) findViewById(etCreateAccUsername);
etEmail = (EditText) findViewById(etCreateAccEmail);
final TextView createAcc = (TextView) findViewById(R.id.tvCreateAcc);
createAcc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* creating this intent shows where you're starting and
where you want to go, we want to get the to the create account page
called RegisterUser.java
first line creates the intent
*/
Intent createIntent = new Intent(MainActivity.this, CreateAccount.class);
//second line makes the intent actually happen .startActivity
MainActivity.this.startActivity(createIntent);
}
});
}
public void signup(View v) {
String UserName = etUserName.getText().toString();
String PassWord = etPassWord.getText().toString();
String Email = etEmail.getText().toString();
Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new SignupActivity(this).execute(UserName, PassWord, Email);
}
}
Here is my SignupActivity.java:
package android.capstone.registerlogin;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String userName = arg0[0];
String passWord = arg0[1];
String eMail = arg0[2];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?username=" + URLEncoder.encode(userName, "UTF-8");
data += "&password=" + URLEncoder.encode(passWord, "UTF-8");
data += "&email=" + URLEncoder.encode(eMail, "UTF-8");
link = "http://cgi.soic.indiana.edu/~gabschle/signup.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Data inserted successfully. Signup successful.", Toast.LENGTH_SHORT).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Data could not be inserted. Signup failed." + jsonStr, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
Here is my CreateAccount.java:
package android.capstone.registerlogin;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import static android.capstone.registerlogin.R.id.etCreateAccEmail;
import static android.capstone.registerlogin.R.id.etCreateAccPassword;
import static android.capstone.registerlogin.R.id.etCreateAccUsername;
public class CreateAccount extends Activity {
private EditText etUserName, etPassWord, etEmail;
private Button mButton;
//private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_account);
etPassWord = (EditText) findViewById(etCreateAccPassword);
etUserName = (EditText) findViewById(etCreateAccUsername);
etEmail = (EditText) findViewById(etCreateAccEmail);
final String UserName = etUserName.getText().toString();
final String PassWord = etPassWord.getText().toString();
final String Email = etEmail.getText().toString();
mButton = (Button) findViewById(R.id.bCreateAccSignUp);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new SignupActivity(CreateAccount.this).execute(UserName, PassWord, Email);
}
});
}
public void signup(View v) {
String UserName = etUserName.getText().toString();
String PassWord = etPassWord.getText().toString();
String Email = etEmail.getText().toString();
Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new SignupActivity(this).execute(UserName, PassWord, Email);
}
}
Here is my PHP file:
<?php
$con=mysqli_connect("db.soic.indiana.edu","caps16_team19","capstoneteam19","caps16_team19");
if (mysqli_connect_errno($con))
{
echo '{"query_result":"ERROR"}';
}
$userName = $_GET['username'];
$passWord = $_GET['password'];
$tDate = $_GET['date'];
$tDate = date('Y-m-d');
$eMail =$_GET['email'];
if($eMail == null) {
echo '{"query_result":"FAILURE"}';
} else {
$result = mysqli_query($con,"INSERT INTO account (username, password, activated, email) VALUES ('$userName', '$passWord', '$tDate','$eMail')");
if($result == true) {
echo '{"query_result":"SUCCESS"}';
}
else{
echo '{"query_result":"FAILURE"}';
}
}
mysqli_close($con);
?>
Let me know if you need additional files!
Thanks for your help!
you're getting the values from the text fields before they'are assigned (during onCreate).
Change to this:
mButton = (Button) findViewById(R.id.bCreateAccSignUp);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String UserName = etUserName.getText().toString();
String PassWord = etPassWord.getText().toString();
String Email = etEmail.getText().toString();
//Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new SignupActivity(CreateAccount.this).execute(UserName, PassWord, Email);
}
});
ps.: that context inside SignupActivity is a memory leak.
Since I finally figured out that the registerReceiver() method is usually running on the UI-Thread, I now want to change that. I just need some advice of how I could do that.
How would I be able to change registerReceiver() to stop freezing my app?
My doInBackground() method from the AsyncTask, runs another method that is using the registerReceiver(mReceiver, filter) method (both variables are already defined). But I want to keep seeing my ProgressDialog instead of making the app freezing.
I read about using a Handler and a new Thread, but I need some help there.
Thanks in advance.
Code:
package ch.scs.mod.tools.messagegenerator.business;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.telephony.SmsManager;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import ch.scs.mod.tools.messagegenerator.R;
import ch.scs.mod.tools.messagegenerator.model.Testcase;
import ch.scs.mod.tools.messagegenerator.model.Testset;
public class ReportActivity extends Activity implements OnClickListener {
private static final String TAG = "ReportActivity";
private TextView title;
private TextView lblReport;
private TextView lblEmail;
private TableLayout tblReport;
private Button btnBack;
private Testset testset;
private Testcase testcase;
private List<Testcase> testcases = new ArrayList<Testcase>();
private String number;
private String apn = "not used";
private String error;
private ArrayList<String> resultarray = new ArrayList<String>();
private ProgressDialog progressdialog;
private boolean running = false;
public enum State {
UNKNOWN, CONNECTED, NOT_CONNECTED
}
private ConnectivityManager mConnMgr;
private PowerManager.WakeLock mWakeLock;
private ConnectivityBroadcastReceiver mReceiver;
private NetworkInfo mNetworkInfo;
private State mState;
private boolean mListening;
private boolean mSending;
private SendMms sendMms = SendMms.getInstance();
private MMSTest myTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.report);
title = (TextView) findViewById(R.id.lblTitle);
lblReport = (TextView) findViewById(R.id.lblReport);
lblEmail = (TextView) findViewById(R.id.lblMmsEmail);
tblReport = (TableLayout) findViewById(R.id.tblReport);
btnBack = (Button) findViewById(R.id.btnBack);
progressdialog = new ProgressDialog(this);
progressdialog.setTitle("Please wait...");
progressdialog.setMessage("Sending...");
progressdialog.setCancelable(false);
Typeface tf = Typeface.createFromAsset(getAssets(),
"fonts/TheSansB_TT4_App.ttf");
title.setTypeface(tf);
lblEmail.setTypeface(tf);
lblReport.setTypeface(tf);
btnBack.setTypeface(tf);
lblEmail.setText(Html
.fromHtml("<a href=\'mailto:mathias.hubacher#swisscom.com\'>mathias.hubacher#swisscom.com</a>"));
lblEmail.setMovementMethod(LinkMovementMethod.getInstance());
btnBack.setOnClickListener(this);
testset = (Testset) this.getIntent().getSerializableExtra("testset");
number = (String) this.getIntent().getStringExtra("number");
lblReport.setText(getResources().getString(R.string.reportText1) + " "
+ number + " " + getResources().getString(R.string.reportText2));
testcases = testset.getTestcases();
resultarray.clear();
// Creating Views for Asynctask
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
HorizontalScrollView hsv = new HorizontalScrollView(this);
sv.setLayoutParams(new ScrollView.LayoutParams(ScrollView.LayoutParams.MATCH_PARENT, getWindowManager().getDefaultDisplay().getHeight()/2));
sv.setVerticalScrollBarEnabled(true);
sv.setHorizontalScrollBarEnabled(true);
sv.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
hsv.setLayoutParams(new HorizontalScrollView.LayoutParams(HorizontalScrollView.LayoutParams.MATCH_PARENT, HorizontalScrollView.LayoutParams.MATCH_PARENT));
hsv.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
ll.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
ll.setOrientation(LinearLayout.VERTICAL);
for (Testcase testc : testcases) {
TableRow tr = new TableRow(this);
TextView tv = new TextView(this);
TextView tvok = new TextView(this);
TextView tverror = new TextView(this);
tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
tv.setText(testc.getName() + " ");
tv.setTextColor(getResources().getColor(R.color.white));
tr.addView(tv);
tvok.setText("Sending...");
tvok.setTextColor(getResources().getColor(R.color.white));
tverror.setText("");
tverror.setTextColor(getResources().getColor(R.color.orange));
tr.addView(tvok);
tr.addView(tverror);
ll.addView(tr);
testc.setTextView(tv);
testc.setTextViewOk(tvok);
testc.setTextViewError(tverror);
}
hsv.addView(ll);
sv.addView(hsv);
tblReport.addView(sv);
myTask = new MMSTest();
myTask.execute();
}
private void createSms(List<Testcase> tcs) {
for (Testcase testc : tcs) {
error = "";
if (!testc.isExecute()) {
resultarray.add(getResources().getString(R.string.notExe));
resultarray.add(error);
} else {
sendSms(number, testc);
if (testc.isSuccsess()) {
resultarray.add(getResources().getString(R.string.ok));
resultarray.add(error);
} else {
resultarray.add(getResources().getString(R.string.failed));
resultarray.add(error);
}
}
testc.setRunning(true);
myTask.onProgressUpdate(resultarray.get(resultarray.size()-2), resultarray.get(resultarray.size()-1));
}
}
private class MMSTest extends AsyncTask<String, String, ArrayList<String>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mReceiver = new ConnectivityBroadcastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mReceiver, filter);
// progressdialog.show();
}
#Override
protected ArrayList<String> doInBackground(String... params) {
if (testset.getType().equals("sms")) {
Log.v(TAG, "Testtype SMS");
createSms(testcases);
} else if (testset.getType().equals("mms")) {
Log.v(TAG, "Testtype MMS");
mListening = true;
mSending = false;
mConnMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// mReceiver = new ConnectivityBroadcastReceiver();
apn = (String) ReportActivity.this.getIntent().getStringExtra("apn");
startMms();
} else {
lblReport.setText("Error Testset Type not valid");
}
return resultarray;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
for (Testcase testc : testcases) {
if (testc.getRunning()) {
TextView tvok = testc.getTextViewOk();
TextView tverror = testc.getTextViewError();
if (testc.isExecute()) {
if (testc.isSuccsess()) {
tvok.setText(values[0]);
tvok.setTextColor(getResources().getColor(R.color.green));
tverror.setText(values[1]);
tverror.setTextColor(getResources().getColor(R.color.orange));
}
else {
tvok.setText(values[0]);
tvok.setTextColor(getResources().getColor(R.color.red));
tverror.setText(values[1]);
tverror.setTextColor(getResources().getColor(R.color.white));
}
}
else {
tvok.setText(values[0]);
tvok.setTextColor(getResources().getColor(R.color.red));
tverror.setText(values[1]);
tverror.setTextColor(getResources().getColor(R.color.white));
}
testc.setRunning(false);
break;
}
}
}
#Override
protected void onPostExecute(ArrayList<String> result) {
super.onPostExecute(result);
// int r = 0;
// for (Testcase testc : testcases) {
// TextView tvok = testc.getTextViewOk();
// TextView tverror = testc.getTextViewError();
// if (testc.isExecute()) {
// if (testc.isSuccsess()) {
// tvok.setText(result.get(r));
// tvok.setTextColor(getResources().getColor(R.color.green));
// tverror.setText(result.get(r+1));
// tverror.setTextColor(getResources().getColor(R.color.orange));
// }
// else {
// tvok.setText(result.get(r));
// tvok.setTextColor(getResources().getColor(R.color.red));
// tverror.setText(result.get(r+1));
// tverror.setTextColor(getResources().getColor(R.color.white));
// }
// }
// else {
// tvok.setText(result.get(r));
// tvok.setTextColor(getResources().getColor(R.color.red));
// tverror.setText(result.get(r+1));
// tverror.setTextColor(getResources().getColor(R.color.white));
// }
// r = r + 2;
// }
// progressdialog.dismiss();
}
}
private void sendMms() {
int responseCode=0;
for (Testcase testc : testcases) {
error = "";
if (testc.isExecute()) {
File file = new File(Environment.getExternalStorageDirectory(), ".MODTest/" + testc.getContentFile());
if (file.exists()) {
if (file.length() > 300000) {
Log.v(TAG, "File Length="+ Long.toString(file.length()));
error=getResources().getString(R.string.warningFileSize);
}
responseCode = sendMms.startMms(testc.getSubject(), number, apn, testc.getContentFile(), testc.getContentType(), getApplicationContext());
Log.v(TAG,"Test: "+ testc.getName() + " / Response code: " + Integer.toString(responseCode));
if (responseCode == 200) {
testc.setSuccsess(true);
responseCode = 0;
} else {
testc.setSuccsess(false);
error =Integer.toString(responseCode);
}
} else {
testc.setSuccsess(false);
error =getResources().getString(R.string.errorNoFile);
}
if (testc.isSuccsess()) {
resultarray.add(getResources().getString(R.string.ok) + " ");
resultarray.add(error);
} else {
resultarray.add(getResources().getString(R.string.failed) + " ");
resultarray.add(error);
}
} else {
resultarray.add(getResources().getString(R.string.notExe));
resultarray.add(error);
}
testc.setRunning(true);
myTask.onProgressUpdate(resultarray.get(resultarray.size()-2), resultarray.get(resultarray.size()-1));
}
endMmsConnectivity();
mSending = false;
mListening = false;
}
public void startMms() {
for (Testcase tcs : testcases) {
testcase = tcs;
number = number + "/TYPE=PLMN";
// IntentFilter filter = new IntentFilter();
// filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
// registerReceiver(mReceiver, filter);
try {
// Ask to start the connection to the APN. Pulled from Android
// source code.
int result = beginMmsConnectivity();
Log.v(TAG, "Result= " + Integer.toString(result));
if (result != PhoneEx.APN_ALREADY_ACTIVE) {
Log.v(TAG, "Extending MMS connectivity returned " + result
+ " instead of APN_ALREADY_ACTIVE");
// Just wait for connectivity startup without
// any new request of APN switch.
return;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void sendSms(String nr, Testcase tc) {
if (!tc.getBody().equals("")) {
SmsManager sm = SmsManager.getDefault();
sm.getDefault().sendTextMessage(nr, null, tc.getBody(), null, null);
tc.setSuccsess(true);
} else {
tc.setSuccsess(false);
error = getResources().getString(R.string.errorEmptySms);
}
}
#Override
public void onClick(View v) {
if (v.equals(findViewById(R.id.btnBack))) { // Wenn Button zurück
// geklickt wird
Intent startMmsTest = new Intent(ReportActivity.this,
StartActivity.class);
startActivity(startMmsTest);
}
}
protected void endMmsConnectivity() {
// End the connectivity
try {
Log.v(TAG, "endMmsConnectivity");
if (mConnMgr != null) {
mConnMgr.stopUsingNetworkFeature(
ConnectivityManager.TYPE_MOBILE,
PhoneEx.FEATURE_ENABLE_MMS);
}
} finally {
releaseWakeLock();
}
}
protected int beginMmsConnectivity() throws IOException {
// Take a wake lock so we don't fall asleep before the message is
// downloaded.
createWakeLock();
int result = mConnMgr.startUsingNetworkFeature(
ConnectivityManager.TYPE_MOBILE, PhoneEx.FEATURE_ENABLE_MMS);
Log.v(TAG, "beginMmsConnectivity: result=" + result);
switch (result) {
case PhoneEx.APN_ALREADY_ACTIVE:
case PhoneEx.APN_REQUEST_STARTED:
acquireWakeLock();
return result;
}
throw new IOException("Cannot establish MMS connectivity");
}
private synchronized void createWakeLock() {
// Create a new wake lock if we haven't made one yet.
if (mWakeLock == null) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"MMS Connectivity");
mWakeLock.setReferenceCounted(false);
}
}
private void acquireWakeLock() {
// It's okay to double-acquire this because we are not using it
// in reference-counted mode.
mWakeLock.acquire();
}
private void releaseWakeLock() {
// Don't release the wake lock if it hasn't been created and acquired.
if (mWakeLock != null && mWakeLock.isHeld()) {
mWakeLock.release();
}
}
private class ConnectivityBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int responseCode;
String action = intent.getAction();
if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)
|| mListening == false) {
Log.w(TAG, "onReceived() called with " + mState.toString()
+ " and " + intent);
return;
}
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (noConnectivity) {
mState = State.NOT_CONNECTED;
} else {
mState = State.CONNECTED;
}
mNetworkInfo = (NetworkInfo) intent
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
// mOtherNetworkInfo = (NetworkInfo) intent
// .getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
// mReason =
// intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
// mIsFailover =
// intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER,
// false);
// Check availability of the mobile network.
if (mNetworkInfo == null) {
/**
* || (mNetworkInfo.getType() !=
* ConnectivityManager.TYPE_MOBILE)) {
*/
Log.v(TAG, " type is not TYPE_MOBILE_MMS, bail");
return;
}
if (!mNetworkInfo.isConnected()) {
Log.v(TAG, " TYPE_MOBILE_MMS not connected, bail");
return;
} else {
Log.v(TAG, "connected..");
if (mSending == false) {
mSending = true;
sendMms();
}
}
}
}
}
Move it to onProgressUpdate() method, or better , onPostExecute()/onPreExecuteMethod() depending on your need.
These methods run on UI thread and not on the new thread creetaed by the Asynctask
I try to send some text to web and this is my codes , but it's not support utf8
For example آرین Show ????
how can I delete this problem?!
This is supported English ...
FragmentForm
package com.kamalan.phpandroidapi;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
public class FragmentForm extends Fragment {
// An interface to display or dismiss of ProgressBar
public interface OnSendingRequestToServer {
public void DisplayLoding(boolean setVisibility);
}
private final String TAG = "FragmentForm";
private OnSendingRequestToServer onRequestToServer;
private Context context;
private EditText etName;
private EditText etComment;
private RatingBar ratingBar;
private ImageButton ibSubmit;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
onRequestToServer = (OnSendingRequestToServer) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnConnectingToServer interface.");
}
context = activity.getApplicationContext();
Log.d(TAG, "Fragment attached to activity.");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_form, container, false);
etName = (EditText) view.findViewById(R.id.etName);
etComment = (EditText) view.findViewById(R.id.etComment);
ratingBar = (RatingBar) view.findViewById(R.id.ratingBar);
ibSubmit = (ImageButton) view.findViewById(R.id.ibSubmit);
//TextView tvcm = (TextView) view.findViewById(R.id.tvComment);
Log.d(TAG, "Fragment created.");
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ibSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String strName = etName.getText().toString().trim();
if(strName.length() <= 0) {
Toast.makeText(context, "نام خود را وارد کنید", Toast.LENGTH_LONG).show();
return;
}
String strComment = etComment.getText().toString().trim();
if(strComment.length() <= 0) {
Toast.makeText(context, "متن جک را وارد کنید", Toast.LENGTH_LONG).show();
return;
}
int rate = (int) ratingBar.getRating();
if(rate <= 0) {
Toast.makeText(context, "امتیاز جکتان را وارد کنید", Toast.LENGTH_LONG).show();
return;
}
String deviceId = getDeviceId();
new SendFormTask(deviceId, strName, rate, strComment).execute();
}
private TextView findViewById(int tvcomment) {
// TODO Auto-generated method stub
return null;
}
});
}
private String getDeviceId() {
return Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
}
/*----------------------------------------------------------------------------
* This method is responsible for creating another thread in parallel with
* main UI thread in order to send a request to server and get data (if any).
* ---------------------------------------------------------------------------*/
public class SendFormTask extends AsyncTask<Void, Void, Boolean> {
String deviceId, name, comment;
int rate;
SendFormTask(String deviceId, String strName, int rate, String strComment) {
this.deviceId = deviceId;
this.name = strName;
this.rate = rate;
this.comment = strComment;
}
#Override
protected void onPreExecute() {
Log.d(TAG, "SendFormTask is about to start...");
onRequestToServer.DisplayLoding(true);
}
#Override
protected Boolean doInBackground(Void... params) {
boolean status = false;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(LinkManager.getFormAPI(deviceId, name, rate, comment));
Log.d(TAG, "Try to open: " + url.toString());
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
Log.d(TAG, "Response code is: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
if (in != null) {
StringBuilder strBuilder = new StringBuilder();
// Read character by character
int ch = 0;
while ((ch = in.read()) != -1)
strBuilder.append((char) ch);
// get returned message and show it
String response = strBuilder.toString();
Log.d("Server response:", response);
if(response.equalsIgnoreCase("1"))
status = true;
}
in.close();
}
}
catch(MalformedURLException e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return status;
}
#Override
protected void onPostExecute(Boolean result) {
Log.d(TAG, "SendFormTask finished its task.");
onRequestToServer.DisplayLoding(false);
if(result)
Toast.makeText(context, "جک شما ارسال شد, منتظر تایید آن باشید", Toast.LENGTH_LONG).show();
else
Toast.makeText(context, "جک شما ارسال شد , منتظر تایید آن باشید", Toast.LENGTH_LONG).show();
}
}
}
and LinkManager.java for link to web
public class LinkManager {
private final static String API_FORM = "http://example.com/sendjoke.php?p1=###&p2=####&p3=#####&p4=######";
private final static String API_Comment = "http://example.com/index.php?p1=###";
public static String getFormAPI(String deviceId, String name, int rate, String comment) {
String url = API_FORM;
url = url.replaceAll("###", deviceId);
url = url.replaceAll("####", name);
url = url.replaceAll("#####", Integer.toString(rate));
url = url.replaceAll("######", comment);
url = url.replaceAll(" ", "%20");
return url;
}
public static String getCommentAPI(String deviceId) {
String url = API_Comment;
url = url.replaceAll("###", deviceId);
return url;
}
}
Please Help me.
Sry My English is bad.
Try to use urlencoding. like :HttpGet get = new HttpGet(URLEncoder.encode(url,"UTF-8"));
url is the specific urllink.And If You want to use httppost, encode the entity before setEntity