MongoDB mlab connectivity in Android - android

I am very new in android. Creating a new app to connect the android application with MongoDB (mlab.com). I have successfully connected with Java. But in android, I am not getting how to do it. I have checked without AsyncTask but also getting the same error Can anyone help!
Here is my code
import com.mongodb.MongoClient;
import com.mongodb.MongoClientException;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private ProgressDialog pDialog;
EditText et1,et2,et3;
Button b1;
MongoClientURI uri = new MongoClientURI("mongodb://user:malak#ds149309.mlab.com:49309/mydb");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1=(EditText) findViewById(R.id.nameText);
et2 = (EditText) findViewById(R.id.emailText);
et3 =(EditText) findViewById(R.id.mobText);
b1=(Button) findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = et1.getText().toString();
String email = et2.getText().toString();
String mob = et3.getText().toString();
InsertData(name,email);
}
});
}
public void InsertData(final String name, final String email) {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
MongoClient mongoClient = new MongoClient(uri);
Toast.makeText(getApplicationContext(),"Coonected",Toast.LENGTH_LONG).show();
MongoDatabase database = mongoClient.getDatabase("aghori");
Toast.makeText(getApplicationContext(),"Dtabase connected",Toast.LENGTH_LONG).show();
MongoCollection<Document> collection = database.getCollection("sampleCollection");
// collection.insertOne(document);
} catch (MongoClientException e) {
}
return "Data Inserted Successfully";
}
#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(MainActivity.this, "Data Submit Successfully", Toast.LENGTH_LONG).show();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, email);
}
}
When I run this application and click the button to submit it automatically gets stopped. Hvae anyone any idea please help.

Related

how to update one from two radio group from database in android studio

I have a question on radio button. I have two radio groups, first is "tipe" and the other is "status". First both radio groups take the value from database and highlight the radio button value from database. Then I want to update it, for example, if I change the data from "tipe" and then I press the update button, then the value of "tipe" is changed in the database. Unfortunately somehow, the value form "status" is lost, and it goes the other way around, which means I have to click both of them every time I want to update it. What should I do if I want to just update 1 type of radio group, while the other stays the same?
Code Android:
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.annotation.IdRes;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
public class UpdateData extends AppCompatActivity implements View.OnClickListener {
private EditText editTextNamaOPD, editTextAlamatOPD, editTextPenanggung, editTextIdentitas, editTextNomor, editTextMerk,
editTextTipe, editTextModel, editTextOS, editTextProcessor, editTextMemory, editTextSwap, editTextHDD, editTextDimensi,
editTextDaya;
public String Tipe ="";
public String Status1 = "";
RadioGroup status, tipe1;
public RadioButton aktif, mati, tower, rak;
private Button buttonUpdate;
private Button buttonDelete;
private String id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.status_item);
Intent intent = getIntent();
id = intent.getStringExtra(Config.EMP_ID);
//editTextId = (EditText) findViewById(R.id.editTextId);
editTextNamaOPD = (EditText) findViewById(R.id.editTextNamaOPD);
editTextAlamatOPD = (EditText) findViewById(R.id.editTextAlamatOPD);
editTextPenanggung = (EditText) findViewById(R.id.editTextPenanggung);
editTextIdentitas = (EditText) findViewById(R.id.editTextIdentitas);
editTextNomor = (EditText) findViewById(R.id.editTextNomor);
editTextMerk = (EditText) findViewById(R.id.editTextMerk);
//editTextTipe = (EditText) findViewById(R.id.editTextTipe);
editTextModel = (EditText) findViewById(R.id.editTextModel);
editTextOS = (EditText) findViewById(R.id.editTextOS);
editTextProcessor = (EditText) findViewById(R.id.editTextProcessor);
editTextMemory = (EditText) findViewById(R.id.editTextMemory);
editTextSwap = (EditText) findViewById(R.id.editTextSwap);
editTextHDD = (EditText) findViewById(R.id.editTextHDD);
editTextDimensi = (EditText) findViewById(R.id.editTextDimensi);
editTextDaya = (EditText) findViewById(R.id.editTextDaya);
status = (RadioGroup) findViewById(R.id.status1);
tipe1 = (RadioGroup) findViewById(R.id.tipe);
aktif = (RadioButton) findViewById(R.id.aktif);
mati = (RadioButton) findViewById(R.id.mati);
tower = (RadioButton) findViewById(R.id.Tower);
rak = (RadioButton) findViewById(R.id.Rak);
buttonUpdate = (Button) findViewById(R.id.btnUpdate);
buttonDelete = (Button) findViewById(R.id.btnDelete);
buttonUpdate.setOnClickListener(this);
buttonDelete.setOnClickListener(this);
//editTextId.setText(id);
getEmployee();
}
private void getEmployee(){
class GetEmployee extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(UpdateData.this,"Fetching...","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
showEmployee(s);
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequestParam(Config.URL_GET_ALL,"?IDserver="+id);
return s;
}
}
GetEmployee ge = new GetEmployee();
ge.execute();
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.Tower:
if (checked)
Tipe = "Tower";
break;
case R.id.Rak:
if (checked)
Tipe = "Rak";
break;
}
}
public void onRadioButtonClicked2(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.aktif:
if (checked)
Status1 = "Aktif";
break;
case R.id.mati:
if(checked)
Status1 = "Mati";
break;
}
}
private void showEmployee(String json){
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject c = result.getJSONObject(0);
String namaopd = c.getString(Config.TAG_NAMAOPD);
String alamatopd = c.getString(Config.TAG_ALAMATOPD);
String penanggung = c.getString(Config.TAG_PENANGGUNG);
String identitas = c.getString(Config.TAG_IDENTITAS);
String nomor = c.getString(Config.TAG_NOMOR);
String merk = c.getString(Config.TAG_MERK);
String tipe = c.getString(Config.TAG_TIPE);
String model = c.getString(Config.TAG_MODEL);
String os = c.getString(Config.TAG_OS);
String processor = c.getString(Config.TAG_PROCESSOR);
String memory = c.getString(Config.TAG_MEMORY);
String swap = c.getString(Config.TAG_SWAP);
String hdd = c.getString(Config.TAG_HDD);
String dimensi = c.getString(Config.TAG_DIMENSI);
String daya = c.getString(Config.TAG_DAYA);
String status1 = c.getString(Config.TAG_STATUS);
editTextNamaOPD.setText(namaopd);
editTextAlamatOPD.setText(alamatopd);
editTextPenanggung.setText(penanggung);
editTextIdentitas.setText(identitas);
editTextNomor.setText(nomor);
editTextMerk.setText(merk);
//editTextTipe.setText(tipe);
editTextModel.setText(model);
editTextOS.setText(os);
editTextProcessor.setText(processor);
editTextMemory.setText(memory);
editTextSwap.setText(swap);
editTextHDD.setText(hdd);
editTextDimensi.setText(dimensi);
editTextDaya.setText(daya);
if (status1.equals("Mati")) {
mati.setChecked(true);
aktif.setChecked(false);
} else if (status1.equals("Aktif")) {
aktif.setChecked(true);
mati.setChecked(false);
}
if (tipe.equals("Tower")) {
tower.setChecked(true);
rak.setChecked(false);
} else if (tipe.equals("Rak")) {
tower.setChecked(false);
rak.setChecked(true);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void updateEmployee(){
final String nama = editTextNamaOPD.getText().toString().trim();
final String alamat = editTextAlamatOPD.getText().toString().trim();
final String penanggung = editTextPenanggung.getText().toString().trim();
final String identitas = editTextIdentitas.getText().toString().trim();
final String nomor = editTextNomor.getText().toString().trim();
final String merk = editTextMerk.getText().toString().trim();
final String tipe = Tipe.toString();
final String model = editTextModel.getText().toString().trim();
final String os = editTextOS.getText().toString().trim();
final String processor = editTextProcessor.getText().toString().trim();
final String memory = editTextMemory.getText().toString().trim();
final String swap = editTextSwap.getText().toString().trim();
final String hdd = editTextHDD.getText().toString().trim();
final String dimensi = editTextDimensi.getText().toString().trim();
final String daya = editTextDaya.getText().toString().trim();
final String status = Status1.toString();
boolean digitsOnly = TextUtils.isDigitsOnly(nomor);
if(digitsOnly) {
if(nomor.length() == 0){
Toast.makeText(this, "Nomor Tidak Boleh Kosong", Toast.LENGTH_SHORT).show();
}else {
class UpdateEmployee extends AsyncTask<Void, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(UpdateData.this, "Updating...", "Wait...", false, false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(UpdateData.this, s, Toast.LENGTH_LONG).show();
finish();
}
#Override
protected String doInBackground(Void... params) {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put(Config.KEY_EMP_ID, id);
hashMap.put(Config.KEY_NAMAOPD, nama);
hashMap.put(Config.KEY_ALAMATOPD, alamat);
hashMap.put(Config.KEY_PENANGGUNG, penanggung);
hashMap.put(Config.KEY_IDENTITAS, identitas);
hashMap.put(Config.KEY_NOMOR, nomor);
hashMap.put(Config.KEY_MERK, merk);
hashMap.put(Config.KEY_TIPE, tipe);
hashMap.put(Config.KEY_MODEL, model);
hashMap.put(Config.KEY_OS, os);
hashMap.put(Config.KEY_PROCESSOR, processor);
hashMap.put(Config.KEY_MEMORY, memory);
hashMap.put(Config.KEY_SWAP, swap);
hashMap.put(Config.KEY_HDD, hdd);
hashMap.put(Config.KEY_DIMENSI, dimensi);
hashMap.put(Config.KEY_DAYA, daya);
hashMap.put(Config.KEY_STATUS, status);
RequestHandler rh = new RequestHandler();
String s = rh.sendPostRequest(Config.URL_UPDATE_EMP, hashMap);
return s;
}
}
UpdateEmployee ue = new UpdateEmployee();
ue.execute();
}
}else {
Toast.makeText(this, "Nomor Harus Angka", Toast.LENGTH_SHORT).show();
}
}
private void deleteEmployee(){
class DeleteEmployee extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(UpdateData.this, "Updating...", "Wait...", false, false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(UpdateData.this, s, Toast.LENGTH_LONG).show();
finish();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequestParam(Config.URL_DELETE_EMP,"?IDserver="+id);
return s;
}
}
DeleteEmployee de = new DeleteEmployee();
de.execute();
}
private void confirmDeleteEmployee(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure you want to delete this data?");
alertDialogBuilder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
deleteEmployee();
startActivity(new Intent(UpdateData.this,ReadData.class));
}
});
alertDialogBuilder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
public void onClick(View v) {
if(v == buttonUpdate){
updateEmployee();
}
if(v == buttonDelete){
confirmDeleteEmployee();
}
}
}
update sql:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','account');
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
$id = $_POST['IDserver'];
$S_Nama= $_POST['NamaOPD'];
$S_Alamat = $_POST['AlamatOPD'];
$S_Penanggung = $_POST['NamaPenanggungJawab'];
$S_Identitas = $_POST['IdentitasPenanggung'];
$S_Nomor = $_POST['NomorPenanggung'];
$S_Merk = $_POST['MerkServer'];
$S_Tipe = $_POST['TipeServer'];
$S_Model = $_POST['Model'];
$S_Os = $_POST['OS'];
$S_Processor = $_POST['Processor'];
$S_Memory = $_POST['Memory'];
$S_Swap = $_POST['Swap'];
$S_HDD = $_POST['HDD'];
$S_Dimensi = $_POST['Dimensi'];
$S_Daya = $_POST['DayaListrik'];
$S_Status = $_POST['Status'];
$sql = "UPDATE daftarserver SET NamaOPD = '$S_Nama', AlamatOPD = '$S_Alamat', NamaPenanggungJawab = '$S_Penanggung', IdentitasPenanggung = '$S_Identitas', NomorPenanggung = '$S_Nomor', MerkServer = '$S_Merk', TipeServer = '$S_Tipe', Model = '$S_Model', OS = '$S_Os', Processor = '$S_Processor', Memory = '$S_Memory', Swap = '$S_Swap', HDD = '$S_HDD', Dimensi = '$S_Dimensi', DayaListrik = '$S_Daya', Status = '$S_Status' WHERE IDserver = $id;";
if(mysqli_query($con,$sql)){
echo 'Record Updated Successfully';
}
else{
echo 'Something went wrong';
}
mysqli_close($con);
}
?>

Use android sharedpreference in AsyncTask

I have been developing web pages with php and MySQL for years but am new to developing for Android projects. I have searched and read through all previous questions that I found concerning the subject but have not found the answer that works for my project. Currently when I run the app, all I get is errors and no download. I am posting the complete code for my Main Activity and ask if anyone can explain what I have done wrong. The data in sharedpreferences for UserId is a integer and the Date/session is a number string and the Email/eaddress is a string
package com.example.logintest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
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 MainActivity extends AppCompatActivity {
String IgidPreference = "IgidPreference";
String UserId = "userId";
String Date = "session";
//OR SHOULD THE DECLEARATION BE??
//public static final String UserId = "userId";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
new VerifyLogin().execute();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Login.class);
startActivity(intent);
}
});
}
public class VerifyLogin extends AsyncTask<String, Void, String> {
Context ctx;
SharedPreferences pref;
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
if ((pref.contains(UserId)) && (pref.contains(Date))) {
}
String eaddress = arg0[0];
String today = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?Email=" + URLEncoder.encode(eaddress, "UTF-8");
data += "&Date=" + URLEncoder.encode(today, "UTF-8");
link = "http://domain.com/verifylogin.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 userId = jsonObj.getString("user_id");
String session = jsonObj.getString("session");
String error_type = jsonObj.getString("error");
String error_msg = jsonObj.getString("error_msg");
if (error_type.equals("FALSE")) {
pref = context.getSharedPreferences(IgidPreference, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(UserId, userId);
editor.putString(Date, session);
editor.apply();
Intent intent = new Intent(MainActivity.this, Account.class);
startActivity(intent);
} else if (error_type.equals("TRUE")) {
Toast.makeText(context, error_msg, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, error_msg, 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();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I know it has been some time since posting on the topic but I had to replace the computer, along with Android Studio and make all new project.
Here is what I have found to handle the original issue. I am putting comments inside the code to help anyone else who wants to use code for their next project.
public class LoginActivity extends Activity { //Standard Activity code
Button BtnLaunchSigninActivity; //Button to click
private EditText etLoginUserName, etLoginPassword; // data to submit
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etLoginUserName = (EditText) findViewById(R.id.etLoginUserName);
etLoginPassword = (EditText) findViewById(R.id.etLoginPassword);
BtnLaunchSigninActivity = (Button) findViewById(R.id.btnLoginSignin);
BtnLaunchSigninActivity.setOnClickListener(onClickListener);
}
private View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnLoginSignin) {
signin(v);
}
}
};
public void signin(View v) {
String userName = etLoginUserName.getText().toString();
String passWord = etLoginPassword.getText().toString();
Toast.makeText(this, "Signing In...", Toast.LENGTH_SHORT).show();
new SignIn(this).execute(userName, passWord); // Send data to AsyncTask
}
private class SignIn extends AsyncTask<String, Void, String> {
private Context context; // context is for the SignIn()
SignIn(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String userName = arg0[0];
String passWord = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?username=" + URLEncoder.encode(userName, "UTF-8");
data += "&password=" + URLEncoder.encode(passWord, "UTF-8");
link = "url/login.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result; // My php returns jsonobjects
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result; //turn object into string
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String status = jsonObj.getString("status");
String userid = jsonObj.getString("uid");
String hash = jsonObj.getString("security");
Log.d("tag", jsonObj.toString(4));
if (status.equals("Good")) {
Toast.makeText(context, "Sign In successful.", Toast.LENGTH_SHORT).show();
//YOU HAVE TO USE JSONSTR TO GET USERID AND SECHASH FOR UPDATING SHARED PREFERENCES
//DUE TO ANY POSSIBLE DELAYS OF PROCESSING doInBackground() SEND JSON TO NEXT ACTIVITY TO SET PREFERENCES
//ADD THE STRING TO THE INTENT BELOW, THEN PROCESS THE DATA FOR SETTING SHAREDPREFERENCES IN THE NEXT ACTIVITY
Log.d("UserID",userid);
Log.d("SecHash", hash);
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
Bundle extras = new Bundle();
extras.putString("USERID",jsonObj.getString("uid"));
extras.putString("SECHASH",jsonObj.getString("security"));
extras.putString("USERID","userid");
extras.putString("SECHASH","hash");
intent.putExtras(extras);
startActivity(intent);
} else if (status.equals("Wrong")) {
Toast.makeText(context, "Username/Password is incorrect, could not be verified. Sign In failed.", 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();
}
}
}
}
In next activity get the extras from the intent and add them to the sharedPreferences. That is all there is to it.
Thanks to everyone for their assistance before. I hope this will help others who find themselves with the same problem in the future.
In doInBackground() you define a locale variable but use a members variable
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
if ((pref.contains(UserId)) && (pref.contains(Date))) {
}
Since you only assign pref in onPostExecute() you'll get NullPointerExceptions everytime. Also ctx is null and context is not even declared. So make sure you have pref defined as early as possible.
public class VerifyLogin extends AsyncTask<String, Void, String> {
private final SharedPreferences pref;
VerifyLogin() {
pref = getSharedPreferences(IgidPreference, Context.MODE_PRIVATE);
}
[...]
}
But in the end you should not implement it like this at all. You'll leak your activity here!

sending data from edit text with single button

![here there are 3 edit text box. where i am using json to check the login id and password details and another text box is for the selection of the server address. the only criteria is that all these should be done with a single button ie the login button.
can any one help me with the code]1
the code is as follows
package com.example.catxam;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.catxam.JSONParser;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.EditText;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
public class Login extends Activity {
private EditText inputUserid, inputPassword, server;
TextView forgotPassword;
private Button b1;
public String serve;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String Flag = "flag";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.login);
inputUserid = (EditText) findViewById(R.id.Username_edit);
inputPassword = (EditText) findViewById(R.id.User_password);
server = (EditText) findViewById(R.id.serverSelection);
forgotPassword = (TextView) findViewById(R.id.forgotPassword);
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent passForget = new Intent(getApplicationContext(),
ForgotPassword.class);
startActivity(passForget);
}
});
b1 = (Button) findViewById(R.id.loginbutton); // login button
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new CreateNewUser().execute();
new SelectServerAddress().execute();
}
});
}
// this class is for selection of the server address
class SelectServerAddress extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... arg0) {
return null;
}
}
// this class is for the checking of the user login and password
//i.e. of first login and the next consecutive logins
class CreateNewUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Checking..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Checking creditenials
* */
protected String doInBackground(String... args) {
String user = inputUserid.getText().toString();
String pswrd = inputPassword.getText().toString();
//if (serve == "")
//{
//serve = "192.168.0.101/gly_prov_V1";
//}
//else
//{
//serve = "glydenlewis.esy.es";
//}
// URL to check username & password
final String url_check_user = "http://" + serve +"/gly_prov_V1/android_check.php";
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uname", user));
params.add(new BasicNameValuePair("psd", pswrd));
params.add(new BasicNameValuePair("server",serve));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_check_user,
"POST", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
int flag_ck = json.getInt(Flag);
if (success == 1) {
if (flag_ck == 0)
{
//First Time Login By User
Intent i = new Intent(getApplicationContext(), UpdateDetails.class);
startActivity(i);
finish(); // closing this screen
}
else
{
// successfully login
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish(); // closing this screen
}
} else {
Toast.makeText(getApplicationContext(), "Wrong Credentials", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
You can execute tasks in serial manner. Take the output of first task as input to the second task.
But you have to implement a cancel mechanism if the activity is destroyed while your tasks is actually running. a simple approach is to make tasks references as a class member and cancel it when activity's onStop() method is called.
class static SelectServerAddress extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... urls) {
return getAddress(urls[0]);
}
#Override
protected void onPostExecute(String serverAddress) {
// Call login service
mLoginTask = new CreateNewUser(serverAddress);
mLoginTask.execute();
}
}
Edit:
Update button click listener code to this:
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new SelectServerAdress().execute();
}
});
Then update SelectServerAdress class and add this method:
#Override
protected void onPostExecute(String serverAddress) {
serve = serverAddress;
new SelectServerAddress().execute();
}

Quick Unresolved Class Issue

I get an error on line 80 (userFunction.logoutUser(getApplicationContext());) That says userFunction cannot be resolved. I have defined userFunction and have already tried to use the full package name and things, so what can I do to get rid of this error really quick? (Asked this question mostly for future reference since this happens a lot) Thanks!
package com.example.dashboardactivity;
import libary.UserFunctions;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class LoginActivity extends Activity {
public final String TAG = "LoginActivity";
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
// Login button Click Event
Log.i(TAG, "LoginActivity Login button Click Event" );
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new AsyncTask<String, Void, JSONObject>(){
#Override
protected JSONObject doInBackground(String... args) { //This is run on a background thread
String email = args[0];
String password = args[1];
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) { //This is run on the UI thread
if(json != null){
//... update the user interface ...
Log.i(TAG, "checking for login response");
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
libary.DatabaseHandler db = new libary.DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else{
Log.e("LoginTask", "No login response was received");
}
super.onPostExecute(json);
}
}.execute(inputEmail.getText().toString(), inputPassword.getText().toString());
}
});
// Link to Register Screen
Log.i(TAG, "LoginActivity btnLinkToRegister" );
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
}
You've defined UserFunctions userFunction = new UserFunctions(); inside the doInBackground method but are trying to access the variable in onPostExecute.
Try to declare UserFunctions userFunction; outside the doInBackground so that it is accessible to other functions.
new AsyncTask<String, Void, JSONObject>(){
UserFunctions userFunction;
#Override
protected JSONObject doInBackground(String... args) { //This is run on a background thread
userFunction = new UserFunctions();
}
#Override
protected void onPostExecute(JSONObject json) {
userFunction.logoutUser(getApplicationContext());
}
}

Cannot resolve class in same package, async android development using eclipse

This is my first android project so please excuse my ignorance if I have missed something!
I am trying to change a register form using json/php/mysql into using async, the error I am getting is RegisterTask cannot be resolved to a type on this line
new RegisterTask().execute();
My complete code is this:
package com.app.pubcrawlorganiser;
import org.json.JSONException;
import org.json.JSONObject;
import com.app.pubcrawlorganiser.library.DatabaseHandler;
import com.app.pubcrawlorganiser.library.JSONParser;
import com.app.pubcrawlorganiser.library.UserFunctions;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
#SuppressWarnings("unused")
public class RegisterActivity extends Activity
{
Button btnRegister;
Button btnLinkToLogin;
EditText inputFullName;
EditText inputEmail;
EditText inputPassword;
TextView registerErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.registerName);
inputEmail = (EditText) findViewById(R.id.registerEmail);
inputPassword = (EditText) findViewById(R.id.registerPassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
new RegisterTask().execute();
}
}
);
class RegisterTask extends AsyncTask<String, String, String>
{
protected void onPreExecute()
{
super.onPreExecute();
}
protected String doInBackground(String... args)
{
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
try {
if (json.getString(KEY_SUCCESS) != null)
{
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1)
{
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
Intent dashboard = new Intent(getApplicationContext(), Home.class);
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
finish();
}
else
{
registerErrorMsg.setText("Error occured in registration");
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
};}
protected void onPostExecute()
{
btnLinkToLogin.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent i = new Intent(getApplicationContext(),
WelcomeActivity.class);
startActivity(i);
// Close Registration View
finish();
}
});
}
}
Why cant I use a class in the same package?
You can't define an inner class inside a method! Move it outside onCreate() and it should work.
PS: inner classes should be added at the very top of the outer class or at the very bottom. Depending on your coding rules/guidelines. Placing it somewhere in the middle is pretty confusing...

Categories

Resources