I have a method in a library I am creating for a series of apps I am doing. This method will display an input dialog for the user to input a string entry. I am writing this project for android using android studio, and I am writing it in Java.
Here is the Logcat:
2020-11-17 00:44:23.819 6758-6758/com.phoenixhosman.launcher E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.phoenixhosman.launcher, PID: 6758
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:91)
at android.view.ContextThemeWrapper.getResourcesInternal(ContextThemeWrapper.java:127)
at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:121)
at android.content.Context.getString(Context.java:594)
at com.phoenixhosman.phoenixlib.ActivityPhoenixLib.InputDialog(ActivityPhoenixLib.java:97)
at com.phoenixhosman.launcher.ActivityHome.onClick(ActivityHome.java:151)
at android.view.View.performClick(View.java:6603)
at android.view.View.performClickInternal(View.java:6576)
at android.view.View.access$3100(View.java:780)
at android.view.View$PerformClick.run(View.java:26090)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6714)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:503)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:911)
Here in my ActivityHome.java file:
/*
The Phoenix Hospitality Management System
Launcher App Source Code
Main Activity Code File
Copyright (c) 2020 By Troy Marker Enterprises
All Rights Under Copyright Reserved
The code in this file was created for use with the Phoenix Hospitality Management System (PHMS).
Use of this code outside the PHMS is strictly prohibited.
*/
package com.phoenixhosman.launcher;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.phoenixhosman.phoenixapi.*;
import com.phoenixhosman.phoenixlib.ProviderUser;
import com.phoenixhosman.phoenixlib.ActivityPhoenixLib;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.concurrent.atomic.AtomicInteger;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.phoenixhosman.phoenixapi.ManagerSecurityApi.*;
/**
* This activity display links to the other apps in the Phoenix Hospitality
* system, and use authentication to only show those that the user has
* permission to use.
* #author Troy L. Marker
* #version 1.0.0
* #since 0.5.0
*/
public class ActivityHome extends Activity implements View.OnClickListener
{
private String strCoName;
private String strApiUrl;
private String strLockPass;
private EditText etUsername;
private EditText etPassword;
final private static int REQUEST_CODE_1 = 1;
final ActivityPhoenixLib Phoenix = new ActivityPhoenixLib();
/**
* This method will create the activity, read content to display, and show the main activity screen
* Used when the activity is (re)created.
* #param savedInstanceState current saved instance state
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
setContentView(R.layout.activity_home);
etUsername = findViewById(R.id.etUsername);
etPassword = findViewById(R.id.etPassword);
TextView tvWarning = findViewById(R.id.tvWarning);
Button btnLogon = findViewById(R.id.btnLogon);
Button btnLockPass = findViewById(R.id.btnLockPass);
btnLogon.setOnClickListener(this);
btnLockPass.setOnClickListener(this);
#SuppressLint("Recycle") Cursor cursor = getContentResolver().query(Uri.parse("content://com.phoenixhosman.installer.ProviderSettings/settings"), null, null, null, null, null);
assert cursor != null;
if(cursor.moveToFirst()) {
while(!cursor.isAfterLast()) {
strCoName = cursor.getString(cursor.getColumnIndex("coname"));
strApiUrl = cursor.getString(cursor.getColumnIndex("apiurl"));
strLockPass = cursor.getString(cursor.getColumnIndex("lockpass"));
cursor.moveToNext();
}
new ManagerSecurityApi(strApiUrl);
tvWarning.setText(getString(R.string.warning, rtrim(strCoName)));
} else {
Phoenix.Error(getApplicationContext(),getString(R.string.required), false);
}
}
/**
* Override of the onBackPress method from the parent class
* This disables the back button on the device.
*/
#Override
public void onBackPressed() {
Phoenix.Error(ActivityHome.this, getString(R.string.disabled, getString(R.string.back)),false);
}
/**
* This method overrides the parents click listner.
* #param v the view clicked.
*/
#Override
public void onClick(View v) {
Button button = (Button)v;
String buttonText = button.getText().toString();
if (buttonText.equals(getString(R.string.login))) {
if (etUsername.getText().toString().isEmpty() || etPassword.getText().toString().isEmpty()) {
Phoenix.Error(ActivityHome.this, getString(R.string.both_required,getString(R.string.username_password)), false);
} else {
Call<String> call = getInstance().getApi().login(etUsername.getText().toString(), etPassword.getText().toString());
call.enqueue(new Callback<String>() {
#Override
public void onResponse(#NonNull Call<String> call, #NonNull Response<String> response) {
String body = response.body();
try {
assert body != null;
JSONObject obj = new JSONObject(body);
if (obj.optBoolean("success")) {
etUsername.setText("");
etPassword.setText("");
etUsername.requestFocus();
getContentResolver().delete(ProviderUser.CONTENT_URI, null, null);
ContentValues values = new ContentValues();
values.put(ProviderUser.name, obj.optString("username"));
values.put(ProviderUser.grade, obj.optInt("grade"));
values.put(ProviderUser.gradename, obj.optString("gradename"));
values.put(ProviderUser.department, obj.optInt("department"));
values.put(ProviderUser.departmentname, obj.optString("departmentname"));
getContentResolver().insert(ProviderUser.CONTENT_URI, values);
Phoenix.Success(ActivityHome.this, obj.optString("message"), 5);
showApps(obj.optString("username"), obj.optInt("grade"), obj.optString("gradename"), obj.optInt("department"), obj.optString("departmentname"));
} else {
Phoenix.Error(getApplicationContext(), getString(R.string.user_not), false);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(#NonNull Call<String> call, #NonNull Throwable t) {
}
});
}
} else if (buttonText.equals(getString(R.string.admin_access))) {
String LockPass = Phoenix.InputDialog(ActivityHome.this.getApplicationContext(), getString(R.string.input_prompt, getString(R.string.enter_lock_pass)));
if (LockPass.equals(strLockPass)) {
this.getPackageManager().clearPackagePreferredActivities(this.getPackageName());
finish();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
} else {
throw new IllegalStateException(getString(R.string.unexpected) + v.getId());
}
}
/**
* This method will call the App Display Activity
*/
private void showApps(String username, Integer grade, String gradename, Integer department, String departmentname){
Intent intent = new Intent(ActivityHome.this.getApplicationContext(), ActivityApp.class);
intent.putExtra("username", username);
intent.putExtra("grade", String.valueOf(grade));
intent.putExtra("gradename", gradename);
intent.putExtra("department", String.valueOf(department));
intent.putExtra("departmentname", departmentname);
startActivityForResult(intent, REQUEST_CODE_1);
}
/**
* Function to trim whitespace from the end of a string.
* #param s the string to trim
* #return the trimmed string
*/
#NonNull
public static String rtrim(String s) {
AtomicInteger i;
i = new AtomicInteger(s.length() - 1);
while (i.get() >= 0 && Character.isWhitespace(s.charAt(i.get()))) {
i.getAndDecrement();
}
return s.substring(0, i.get() +1);
}
}
And finially, here is my ActivityPhoenixLib.java file:
package com.phoenixhosman.phoenixlib;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import static android.view.View.inflate;
public class ActivityPhoenixLib extends Activity {
/**
* While not needed, this constructor makes calls to the member method of the class
* to clear errors in the editor.
*/
public ActivityPhoenixLib() {
Error(this, "", false);
Success(this,"",0);
String dummy = InputDialog(this, "");
if (dummy.equals("test")) {
}
}
/**
* This method displays a dialog box with an error message and a close button.
* #param strError the error message to display
*/
public void Error(Context context, #NonNull String strError, Boolean exit) {
if (strError.equals("")) {
return;
}
AlertDialog.Builder mBuilder = new AlertDialog.Builder(context);
View view = inflate(context, R.layout.dialog_error, null);
Button btnExit = view.findViewById(R.id.btnExitButton);
Button btnError = view.findViewById(R.id.btnErrorMessage);
btnError.setText(strError);
mBuilder.setView(view);
AlertDialog dialog = mBuilder.create();
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
dialog.show();
btnExit.setOnClickListener(v -> {
dialog.dismiss();
if (exit) System.exit(0);
});
}
/**
* This method displays a dialog box with a message and a close button.
* It also has an auto close function to auto close after a specified number of seconds.
* #param strMessage the message to display
*/
public void Success(Context context, #NonNull String strMessage, Integer autoclose) {
if (strMessage.equals("")) {
return;
}
AlertDialog.Builder mBuilder = new AlertDialog.Builder(context);
View view = inflate(context, R.layout.dialog_success, null);
Button btnExit = view.findViewById(R.id.btnButton);
Button btnError = view.findViewById(R.id.btnMessage);
btnError.setText(strMessage);
mBuilder.setView(view);
AlertDialog dialog = mBuilder.create();
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
dialog.show();
btnExit.setOnClickListener(v -> dialog.dismiss());
new Handler().postDelayed(dialog::dismiss, autoclose * 1000);
}
/**
* This method show an input box to get string input from the user.
* #param strPrompt - the dialog prompt
*/
public String InputDialog(Context context, String strPrompt) {
if (strPrompt.equals("")) {
return "";
}
AlertDialog.Builder mBuilder = new AlertDialog.Builder(context);
final String[] retval = new String[1];
View view = inflate(context, R.layout.dialog_input, null);
TextView txtPrompt = view.findViewById(R.id.txtPrompt);
EditText edtLockPass = view.findViewById(R.id.edtLockPass);
Button btnEnter = view.findViewById(R.id.btnEnter);
--> Line 97 <-- txtPrompt.setText(getString(R.string.input_prompt, strPrompt));
mBuilder.setView(view);
AlertDialog dialog = mBuilder.create();
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
dialog.show();
btnEnter.setOnClickListener(v -> {
if (edtLockPass.getText().toString().equals("")) {
retval[0] = "";
} else {
retval[0] = edtLockPass.getText().toString();
}
});
dialog.dismiss();
return retval[0];
}
}
I have tried several different things. I am going on the assumption that the context is not being passed to the InputDialog function, and I have tried different way of pass the context to the function: this. ActivityHome.this, getApplicationContext, and none of them seemed to work. Is there something I have nbot considered? Any help would be appreciated. Thanks.
Edit-In responce to one of the comments about my getString usage, on the page linked here my usage is documented, the second string is is the argument object for the formatting string.
Edit 2: I also tried to use a single parameter getSting on the line in question, and got the smae error.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to pass through a username (EMAIL) into the createLoginSession within my SharedPreferencesManagement class. When I try to execute this on the login i'm getting an error which states that "createLoginSession(java.lang.String) on a null object reference".
public class SessionManagement {
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "AndroidHivePref";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "email";
// Constructor
public SessionManagement(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
/**
* Create login session
* */
public void createLoginSession(String email){
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
// Storing email in pref
editor.putString(KEY_EMAIL, email);
// commit changes
editor.commit();
}
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything
* */
public void checkLogin(){
// Check login status
if(!this.isLoggedIn()){
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, ActivityLogin.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
// return user
return user;
}
/**
* Clear session details
* */
public void logoutUser(){
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Loing Activity
Intent i = new Intent(_context, ActivityLogin.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
/**
* Quick check for login
* **/
// Get Login State
public boolean isLoggedIn(){
return pref.getBoolean(IS_LOGIN, false);
}
The code for the Activity Login is as follows:
package com.example.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatTextView;
import android.util.Log;
import android.view.View;
import com.example.myapplication.R;
import com.example.myapplication.InputValidation;
import com.example.myapplication.DatabaseHelper;
public class ActivityLogin extends AppCompatActivity implements
View.OnClickListener {
private final AppCompatActivity activity = ActivityLogin.this;
private NestedScrollView nestedScrollView;
private TextInputLayout textInputLayoutEmail;
private TextInputLayout textInputLayoutPassword;
private TextInputEditText textInputEditTextEmail;
private TextInputEditText textInputEditTextPassword;
private AppCompatButton appCompatButtonLogin;
private AppCompatTextView textViewLinkRegister;
private InputValidation inputValidation;
private DatabaseHelper databaseHelper;
public String email;
//Session Manager Class
SessionManagement session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
initViews();
initListeners();
initObjects();
}
/**
* This method is to initialize views
*/
private void initViews() {
nestedScrollView = (NestedScrollView) findViewById(R.id.nestedScrollView);
textInputLayoutEmail = (TextInputLayout)
findViewById(R.id.textInputLayoutEmail);
textInputLayoutPassword = (TextInputLayout)
findViewById(R.id.textInputLayoutPassword);
textInputEditTextEmail = (TextInputEditText)
findViewById(R.id.textInputEditTextEmail);
textInputEditTextPassword = (TextInputEditText)
findViewById(R.id.textInputEditTextPassword);
appCompatButtonLogin = (AppCompatButton)
findViewById(R.id.appCompatButtonLogin);
textViewLinkRegister = (AppCompatTextView)
findViewById(R.id.textViewLinkRegister);
;
}
/**
* This method is to initialize listeners
*/
private void initListeners() {
appCompatButtonLogin.setOnClickListener(this);
textViewLinkRegister.setOnClickListener(this);
}
/**
* This method is to initialize objects to be used
*/
private void initObjects() {
databaseHelper = new DatabaseHelper(activity);
inputValidation = new InputValidation(activity);
}
/**
* This implemented method is to listen the click on view
*
* #param v
*/
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.appCompatButtonLogin:
verifyFromSQLite();
break;
case R.id.textViewLinkRegister:
// Navigate to RegisterActivity
Intent intentRegister = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(intentRegister);
break;
}
}
/**
* This method is to validate the input text fields and verify login
credentials from SQLite
*/
private void verifyFromSQLite() {
if (!inputValidation.isInputEditTextFilled(textInputEditTextEmail,
textInputLayoutEmail, getString(R.string.error_message_email))) {
return;
}
if (!inputValidation.isInputEditTextEmail(textInputEditTextEmail,
textInputLayoutEmail, getString(R.string.error_message_email))) {
return;
}
if (!inputValidation.isInputEditTextFilled(textInputEditTextPassword,
textInputLayoutPassword, getString(R.string.error_message_email))) {
return;
}
if
(databaseHelper.checkUser(textInputEditTextEmail.getText().toString().trim()
, textInputEditTextPassword.getText().toString().trim())) {
email = textInputEditTextEmail.getText().toString().trim();
Intent accountsIntent = new Intent(activity, MainMenuActivity.class);
accountsIntent.putExtra("EMAIL",
textInputEditTextEmail.getText().toString().trim());
session.createLoginSession(email);
emptyInputEditText();
startActivity(accountsIntent);
} else {
// Snack Bar to show success message that record is wrong
Snackbar.make(nestedScrollView,
getString(R.string.error_valid_email_password), Snackbar.LENGTH_LONG).show();
}
}
/**
* This method is to empty all input edit text
*/
private void emptyInputEditText() {
textInputEditTextEmail.setText(null);
textInputEditTextPassword.setText(null);
}
}
The error is on the line "session.createLoginSession("EMAIL");" as this is being passed in as a null value.
the problem is that you don't instantiate your SessionManagement object anywhere in your Activity. Implement this statement in your initObjects method session = SessionManagement(this);
This is my first question here on stack overflow, so please forgive me for any oversight or formatting errors. This issue seems simple enough, but I am not able to "put the pieces together" for some reason. I am also learning java and android studio as I go, so please forgive and educate on any bad code.
I need to gather data from my barcode scanning app, submit it to a variable, and then pass that variable through my database to fetch information based on the UPC code. I am using the ZXing library for the barcode scanner, with the handleResult method to capture the initial data.
I have the data collected within the SimpleScanner activity, but I can't figure out how to use that variable in a SQlite query. Below are the main classes I am using.
Any help would be appreciated. I can query the entire database just fine, but I need to look up the rows that match the actual item I am scanning. Thanks again!
SimpleScannerActivity.java
package com.example.android.dropr;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;
import com.google.zxing.Result;
import java.util.ArrayList;
import java.util.List;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class SimpleScannerActivity extends MainActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
mScannerView = new ZXingScannerView(this); // Programmatically initialize the scanner view
setContentView(mScannerView); // Set the scanner view as the content view
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera on resume
}
#Override
public void onPause () {
super.onPause();
mScannerView.stopCamera(); // Stop the camera on pause
}
#Override
public void handleResult(Result rawResult) {
String TAG = "Dropr";
/**
* Create Alert Dialog, so that user has time to read the information within.
*/
AlertDialog.Builder scanInfo = new AlertDialog.Builder(this);
String messageContent = "Content - " + rawResult.getText();
String messageFormat = "Format - " + rawResult.getBarcodeFormat().toString() + ".";
scanInfo.setTitle("Scan Information:");
scanInfo.setMessage(messageContent + "\n" + messageFormat);
scanInfo.setCancelable(true);
scanInfo.setPositiveButton(
"OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
// IF you would like to resume scanning, call this method below:
// Handle the data
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mScannerView.resumeCameraPreview(SimpleScannerActivity.this);
}
}, 1000);
}
});
AlertDialog showInfo = scanInfo.create();
showInfo.show();
// Do something with the result here
Log.v(TAG, rawResult.getText());
Log.v(TAG, rawResult.getBarcodeFormat().toString());
}
}
DatabaseAccess.java
package com.example.android.dropr;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class DatabaseAccess {
private SQLiteOpenHelper openHelper;
private SQLiteDatabase database;
private static DatabaseAccess instance;
private SimpleScannerActivity scannerActivity = new SimpleScannerActivity();
/**
* Private constructor to avoid object creation from outside classes.
*
* #param context
*/
protected DatabaseAccess(Context context) {
this.openHelper = new DatabaseOpenHelper(context);
}
/**
* Return a singleton instance of DatabaseAccess.
*
* #param context
* #return the instance of DatabaseAccess
*/
public static DatabaseAccess getInstance(Context context) {
if (instance == null) {
instance = new DatabaseAccess(context);
}
return instance;
}
/**
* Open the database connection
*/
public void open() {
this.database = openHelper.getWritableDatabase();
}
/**
* Close the database connection
*/
public void close() {
if (database != null) {
this.database.close();
}
}
/**
* Read all quotes from the database.
*
* #return a list of quotes
*/
public List<String> getCodes() {
List<String> list = new ArrayList<>();
Cursor cursor = database.rawQuery("SELECT name, upc14 FROM Barcodes", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(0));
list.add(cursor.getString(1));
cursor.moveToNext();
}
cursor.close();
return list;
}
}
I finally came up with a solution, thanks to #muratgu! I created another method that creates and stores a variable for the scanned data, and passes the variable through a query.
/**
* read a single record from the database the matches the UPC-A code scanned.
* if there is no match, do nothing.
* #param rawContent
* #return a brand name based on the matching UPC-A code that was scanned.
*/
public String getInfo(String rawContent) {
String TAG = "Getinfo():";
String content = "00" + rawContent;
String brandName = "";
Cursor cursor = database.rawQuery("SELECT name, upc12 from Barcodes WHERE '" + content + "' = upc12", null);
if(cursor.getCount() > 0) {
cursor.moveToFirst();
brandName = cursor.getString(cursor.getColumnIndex("name"));
cursor.close();
} else {
Log.v(TAG, "uh oh, something went wrong in the if loop! ");
}
return brandName;
}
This method gets called in the SimpleScannerActivity.java file, where the scanned data can be passed through the variable. The method returns the name of the item, which is then placed in the dialog box. Exactly what I needed.
Thanks again, #muratgu! you gave me enough information that I could solve the problem myself. I just had to think on it for a bit!
I have search now for hours through the internet and have found nothing substantial so far. The thing that I want to do is a multi choice preference view, that disables the last item and reenables it, if it is not alone anymore.
I through so far about taking the super class force read the private variables in there to write my own onPrepareDialogBuilder(AlertDialog.Builder builder). Which is configuring its own OnMultiChoiceClickListener that jumps in, in the moment where has only one item left. The problem here is, that I use a bad practice force read of a private variable and that I have so far no idea how to get the checkbox item and how to disable it. But I think looking even deeper into the Android SDK will solve this problem.
At the end, if nothing works, solving the problem with doing an overwrite the OnPreferenceChangeListener to display a toast if the user has less than one item selected. But user friendliness is a high value, that needs to be earned and that often isn't easy.
Thx.
import android.content.Context;
import android.preference.MultiSelectListPreference;
import android.util.AttributeSet;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import georg.com.flironetest_01.Variables.Units;
/**
* Created by Georg on 16/03/16.
*/
public class UnitMultipleSelectorPreference extends MultiSelectListPreference {
public UnitMultipleSelectorPreference(Context context, AttributeSet attrs) {
super(context, attrs);
List<CharSequence> humanU = new ArrayList<>();
List<CharSequence> machineU = new ArrayList<>();
Units[] all = Units.values(); // Units is a enum with a rewriten to string statement.
for (Units elem : all) {
humanU.add(elem.toString());
machineU.add(elem.name());
}
setEntries(humanU.toArray(new CharSequence[humanU.size()]));
setEntryValues(machineU.toArray(new CharSequence[machineU.size()]));
Set<String> mU = new HashSet<>();
mU.add(Units.C.name());
mU.add(Units.K.name());
setDefaultValue(mU);
}
}
Okay. To answer my own question here after the motto "self is the man": I ended up with programming my own preference panel. Below is the code. If somebody likes to look over it and give some times how to make it even more stable: feel free.
But to sum up what I did: I created my own ArrayAdapter. But DialogPreference didn't allowed me to create my own multi selector. You need to change the final dialog fragment to create a working multi selector list (see here: https://stackoverflow.com/a/17907379/5759814). That is not an easy task if you work with the DialogPreferences. The reason is these few amounts of code:
/**
* Shows the dialog associated with this Preference. This is normally initiated
* automatically on clicking on the preference. Call this method if you need to
* show the dialog on some other event.
*
* #param state Optional instance state to restore on the dialog
*/
protected void showDialog(Bundle state) {
Context context = getContext();
mWhichButtonClicked = DialogInterface.BUTTON_NEGATIVE;
mBuilder = new AlertDialog.Builder(context)
.setTitle(mDialogTitle)
.setIcon(mDialogIcon)
.setPositiveButton(mPositiveButtonText, this)
.setNegativeButton(mNegativeButtonText, this);
View contentView = onCreateDialogView();
if (contentView != null) {
onBindDialogView(contentView);
mBuilder.setView(contentView);
} else {
mBuilder.setMessage(mDialogMessage);
}
onPrepareDialogBuilder(mBuilder);
getPreferenceManager().registerOnActivityDestroyListener(this);
// Create the dialog
final Dialog dialog = mDialog = mBuilder.create();
if (state != null) {
dialog.onRestoreInstanceState(state);
}
if (needInputMethod()) {
requestInputMethod(dialog);
}
dialog.setOnDismissListener(this);
dialog.show();
}
As you can see here is a method triggered to change my dialog builder with onPrepareDialogBuilder, but it doesn't seem like that there is any other function triggered afterwards, that would allow me to change the dialog directly after its creation. And the second idea of changing the onPrepareDialogBuilder so that I can init everything there, doesn't really help, because I end up with displayed dialog windows. That lead me to my decision of creating my completely own Preference class. With that decision I loose all those nice prepared functions like onRestoreInstanceState and Co, but I now have an application with a much more persistent flow, that doesn't do any stupid things when I select zero units for my thermal view.
Below the non commented code. I'm sorry, but I think its simple enough for everybody who landing here.
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.preference.Preference;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import georg.com.flironetest_01.Variables.Units;
/**
* Created by Georg on 16/03/16.
*/
public class UnitMultipleSelectorPreference extends Preference implements DialogInterface.OnClickListener, Preference.OnPreferenceClickListener {
String[] human_entries = null;
String[] machine_entries = null;
public SharedPreferences prev;
public UnitMultipleSelectorPreference(Context context, AttributeSet attrs) {
super(context, attrs);
prev = getSharedPreferences();
List<String> humanU = new ArrayList<>();
List<String> machineU = new ArrayList<>();
Units[] all = Units.values();
for (Units elem : all) {
humanU.add(elem.toString());
machineU.add(elem.name());
}
human_entries = humanU.toArray(new String[humanU.size()]);
machine_entries = machineU.toArray(new String[machineU.size()]);
Set<String> mU = new HashSet<>();
mU.add(Units.C.name());
mU.add(Units.K.name());
setDefaultValue(mU);
setOnPreferenceClickListener(this);
}
boolean[] selected = new boolean[0];
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
if (prev == null)
return;
if (human_entries == null || machine_entries == null || human_entries.length != machine_entries.length ) {
throw new IllegalStateException(
"ListPreference requires an entries array and an entryValues array which are both the same length");
}
selected = new boolean[human_entries.length];
for (int i = 0; i < human_entries.length; i++)
selected[i] = prefSet.contains(machine_entries[i]);
String[] stringObj = new String[human_entries.length];
int i = 0;
for(CharSequence ch : human_entries)
stringObj[i++] = ch.toString();
builder.setAdapter(new MyAdapter(getContext(), android.R.layout.simple_list_item_multiple_choice, stringObj), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog mDialog = builder.create();
mDialog.getListView().setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
mDialog.getListView().setItemsCanFocus(false);
mDialog.getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Manage selected items here
ListView mParent = (ListView)parent;
if (mParent.getCheckedItemCount() >= 1)
selected[position] = mParent.isItemChecked(position);
if (mParent.getCheckedItemCount() == 0)
mParent.setItemChecked(position, true);
}
});
mDialog.show();
i = 0;
for (boolean select : selected)
mDialog.getListView().setItemChecked(i++, select);
}
#Override
public boolean onPreferenceClick(Preference preference) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(getContext());
mBuilder.setTitle(getTitle())
.setPositiveButton(android.R.string.ok, this)
.setNegativeButton(android.R.string.cancel, this);
onPrepareDialogBuilder(mBuilder);
return true;
}
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(), "W:"+which + " | " + Arrays.toString(selected), Toast.LENGTH_SHORT).show();
switch (which) {
case -1:
if (isPersistent()) {
prefSet = new HashSet<>();
for (int i = 0; i < selected.length; i++) {
if (selected[i])
prefSet.add(machine_entries[i]);
}
getEditor().putStringSet(getKey(), prefSet).apply();
Toast.makeText(getContext(), "W:"+which + " | " + getSharedPreferences().getStringSet(getKey(),null).toString(), Toast.LENGTH_SHORT).show();
}
return;
}
}
public class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, int textViewResourceId, String[] objects) {
super(context, textViewResourceId, objects);
}
#Override
public boolean isEnabled(int n) {
return true;
}
}
Set<String> prefSet;
#Override
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
super.onSetInitialValue(restorePersistedValue, defaultValue);
prev = getSharedPreferences();
if(restorePersistedValue) {
prefSet = prev.getStringSet(getKey(), new HashSet<String>());
} else {
try {
prefSet = (Set<String>)defaultValue;
if(isPersistent())
getEditor().putStringSet(getKey(), prefSet);
} catch (ClassCastException e) {
Log.e("ERROR_CAST", "Error casting the default value to Set<String>.");
}
}
}
}
A really simple solution is to set a setOnPreferenceChangeListener and just return false if the new value would be empty.
All of the code is put into onCreatePreferences.
MultiSelectListPreference infoPreference = findPreference("information");
infoPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (size(newValue) == 0){
return false;
}
return true;
}
});
I am relatively new to Java and working with the ArcGIS Runtime SDK for Android. I am making an app where the user selects the parcel id from spinner list. If the user clicks on a 'ZOOM' button the map should zoom to the parcel that was selected. Here is my code:
package gist8010.main;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import com.esri.android.map.MapView;
import com.esri.android.map.ags.ArcGISDynamicMapServiceLayer;
import com.esri.android.map.ags.ArcGISTiledMapServiceLayer;
import com.esri.core.geometry.Envelope;
import com.esri.core.geometry.Point;
import com.esri.core.map.Feature;
import com.esri.core.map.FeatureResult;
import com.esri.core.tasks.query.QueryParameters;
import com.esri.core.tasks.query.QueryTask;
public class Spinner_WalkActivity extends Activity {
MapView mMapView;
Button mBtnZoom;
ArcGISDynamicMapServiceLayer mDynamicLayer;
Spinner mSpnParcels;
String mMapServiceURL = "http://indy14.athena.bcit.ca:8080/"
+ "esri_rest/services/gist_8010_test_ms/MapServer";
int mLotLayerID = 0;
String mLotLayerURL = mMapServiceURL + "/" + mLotLayerID;
String mLotNumColName = "PARCELS_ID";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/** Allow querying on main thread */
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
/** Create spinner and button */
setMapView();
this.mBtnZoom = (Button) findViewById(R.id.btnZoom);
mBtnZoom.setOnClickListener(new OnClickListener() {
/** Upon click of zoom button, invoke th zoomtoFeature Method */
public void onClick(View v) {
zoomToFeature(v);
}
});
this.mSpnParcels = (Spinner) findViewById(R.id.spnParcels);
/** Add Layer to map */
mDynamicLayer = new ArcGISDynamicMapServiceLayer(mMapServiceURL);
mMapView.addLayer(mDynamicLayer);
QueryParameters qryLotNums = new QueryParameters();
qryLotNums.setReturnGeometry(false);
qryLotNums.setOutFields(new String[] { mLotNumColName });
qryLotNums.setWhere(mLotNumColName + ">0");
com.esri.core.tasks.query.QueryTask qtask = new com.esri.core.tasks.query.QueryTask(
mLotLayerURL);
try {
FeatureResult fSet = qtask.execute(qryLotNums);
ArrayList<String> listOfLotsNums = new ArrayList<String>();
Feature tmpFeat;
for (Object featAsObj : fSet) {
tmpFeat = (Feature) featAsObj;
listOfLotsNums.add(tmpFeat.getAttributeValue(mLotNumColName)
.toString());
}
ArrayAdapter<String> adtTmp = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item,
listOfLotsNums);
mSpnParcels.setAdapter(adtTmp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}// of catch
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
mMapView.pause();
}
#Override
protected void onResume() {
super.onResume();
mMapView.unpause();
}
// =============================================================================
// Zooms the map the the MBR of the feature selected in the spinner
// import android.view.View;
// =============================================================================
public void zoomToFeature(View v) {
QueryParameters zoomQuery = new QueryParameters();
zoomQuery.setReturnGeometry(true);
zoomQuery.setOutFields(new String[] { mLotNumColName });
zoomQuery.setWhere(mLotNumColName + "=" + mSpnParcels.getSelectedItem());
QueryTask qtask = new QueryTask(mLotLayerURL);
try {
FeatureResult fset = qtask.execute(zoomQuery);
Feature tmpFeat = (Feature) fset.iterator().next();
Envelope envelope = new Envelope();
envelope.queryEnvelope((Envelope) tmpFeat.getGeometry());
getMapView().setExtent(envelope);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// =============================================================================
// getter for the main map
// =============================================================================
private MapView getMapView() {
// =============================================================================
// if MapView is underlined in red, change the name to match your
// MapView
// =============================================================================
return mMapView;
}
// =============================================================================
// setter for the main map
// =============================================================================
private void setMapView() {
// ========================================================================
// if mapView is underlined in red then sync class-level var names
// if R.id.map is underlined in red ensure that you added the xml
// fragment
// such as "MapView Generic" to a layout
// ========================================================================
mMapView = (MapView) findViewById(R.id.map);
}
}
After attempting to debug, I think my issue is with the Envelope class. The queryEnvelope method accepts a Envelope argument. As you can see, I cast the geometry of the Feature tmpFeat from a geometry type into a Envelope type.
When I run the application on my phone I get an System.Err in my log Cat saying:
java.lang.ClassCastException: com.esri.core.geometry.Polygon cannnot be cast to com.esri.core.geometry.Envelope
Am I doing the casting incorrectly? I cannot think of another way of linking my Envelope instance with the geometry of the feature class i want to zoom to.
Envelop is a child class of com.esri.core.geometry.Geometry, not vice versa. I guess this is why you fail when do the cast.
https://developers.arcgis.com/android/api-reference/reference/com/esri/core/geometry/Envelope.html
As it to your question, I guess envelop is not necessary to zoom to a feature. MapView.zoomToResolution(Point centerPt, double res) or zoomTo(Point centerPt, float factor) may be a better choice. You may find these sample codes helpful:
https://developers.arcgis.com/android/sample-code/geocoding/
I have written a log in function for my android app, I am wanting to make it work on API 17, right now it give a network on main thread exception, which I understand you cant do network operations on the main thread, I have played around with trying to put threads in but it doesn't seem to go. So i am trying a asynctask now
any help suggestions would be great
package khs.studentsupport;
import java.util.HashMap;
import khs.supportapp.library.DatabaseHandler;
import khs.supportapp.library.UserFunctions;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
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 New_Login extends Activity{
// Progress Dialog
private ProgressDialog pDialog;
public String storedEmail="";
public String stroedPW = "";
boolean GCMFlag=false;
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "AndroidHivePref";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_NAME = "name";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "email";
// Constructor
public void SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
/**
* Create login session
* */
public void createLoginSession(String name, String email){
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
// Storing name in pref
editor.putString(KEY_NAME, name);
// Storing email in pref
editor.putString(KEY_EMAIL, email);
// commit changes
editor.commit();
}
// Internet detector
ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
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_STUDENT_ID = "studentUser";
private static String KEY_CREATED_AT = "created_at";
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
//ID of student
user.put(KEY_STUDENT_ID, pref.getString(KEY_STUDENT_ID, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
// return user
return user;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
}
// Response from Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAlldetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(New_Login.this);
pDialog.setMessage("Logging you in. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* getting user details from url
* */
protected String doInBackground(String... args) {
cd = new ConnectionDetector(getApplicationContext());
String storedEmail = Appconfig.stored_user_name.toString();
String stroedPW = Appconfig.stored_password.toString();
// Check if Internet present
if (!cd.isConnectingToInternet())
{
if((inputEmail.toString()==storedEmail)&&(inputPassword.toString()==stroedPW))
{
// 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);
}
}
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
//Auto fill for login only if the user has logged in before
if((Appconfig.stored_user_name.length()>0)&&(Appconfig.stored_password.length()>0))
{
inputEmail.setText(Appconfig.stored_user_name.toString());
inputPassword.setText(Appconfig.stored_password.toString());
}
// Importing all assets like buttons, text fields
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new LoadAlldetails().execute();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
Log.d("Button", "Login");
JSONObject json = userFunction.loginUser(email, password);
//Check to see if user has put in details
if ((email.matches("")||(password.matches(""))))
{
loginErrorMsg.setText("Please enter your details ");
}
else
{ //Checks to see if first time in the app
// launces gcm activity
if (Appconfig.GCMactivity == false) {
Intent intent = new Intent();
intent.setClass(getApplicationContext(),RegisterForGCMActivity.class);
startActivity(intent);
//set to true so GCm register wont show again
Appconfig.GCMactivity=true;
}
else{
// 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
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
Appconfig.stored_user_name=json_user.getString(KEY_EMAIL);
Appconfig.stored_password = password;
if(Appconfig.email_is_set==false)
{
Appconfig.student_ID = json_user.getString(KEY_STUDENT_ID);
}
Appconfig.email_is_set=true;
// 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 Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}}});
GCMFlag = true;
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
return null;
}
public boolean isLoggedIn(){
return pref.getBoolean(IS_LOGIN, false);
}
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting user details
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
}
});
}
}
I see many so far so I will let you know about these but know that there may be more.
First, you call startActivity from a background Thread so you need to add a Context to it. Since its an inner class of Activity you could use
New_Login.this.startActivity(dashboard);
However, you should return data to onPostExecute() and just start the Activity from there.
Another thing I see is that you are trying to update Views from a background Thread which is a no no. You should not try to update them in doInBackground().
You are trying to compare Strings incorrectly
if((inputEmail.toString()==storedEmail)&&(inputPassword.toString()==stroedPW))
it should be
if((inputEmail.toString().equals(storedEmail))&&(inputPassword.toString().equals(stroedPW)))
It looks like you are declaring your Views in your AsyncTask but this should be done in your Activity(most likely in onCreate() or onResume().
Don't use getApplicationContext() unless absolutely necessary. Inside of an onClick() you can use v.getContext() and inside of your Activity but outside of a listener you can use ActivitiyName.this (there are more options there but I will keep that simple for now).
My suggestion, strip out your AsyncTask and get your Activity set up correctly then implement your AsyncTask. And be sure to go through the documentation well.
Activity Docs
AsyncTask Docs