public class SecondActivity2 extends AppCompatActivity {
public static String main_html = "";
public static int second_action = 0;
WebView webView2;
public static taskResearch ndc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
webView2 = (WebView) findViewById(R.id.webView);
String userid = "12345";
try {
ndc = new TaskResearch(userid, "1", "keyword", 5, 4, "orderid", 6, "title", "text");
ndc.execute("");
} catch (Exception e) {
e.printStackTrace();
}
Log.v("htmlg", "taskResearch finished");
}
class TaskResearch extends AsyncTask <String, String, String> {
String deviceId, s_id, keyword, city, s_title, s_text;
int count1, size1, online;
public TaskResearch(String deviceId, String s_id, String keyword, int count1, int size1, String city, int online, String s_title, String s_text){
this.deviceId = deviceId;
this.s_id = s_id;
this.keyword = keyword;
this.city = city;
this.s_title = s_title;
this.s_text = s_text;
this.count1 = count1;
this.size1 = size1;
this.online = online;
}
protected String doInBackground(String... strings) {
String sonuc = "";
runOnUiThread(new Runnable() {
public void run() {
}
});
return "a";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
class html_reader {
#SuppressWarnings("unused")
#JavascriptInterface
public void processHTML(final String html) {
// Log.d("HTMLG", "html: " + html);
// Log.d("HTMLG", "html: " + html);
// html_reader jssil = new html_reader(deviceId, sId, swAfter, swcity);
// webView2.addJavascriptInterface(jssil, "HTMLOUT");
main_html = html;
}
#SuppressWarnings("unused")
#JavascriptInterface
public void ok() {
// Log.d("HTMLG", "html: " + html);
// Log.d("HTMLG", "html: " + html);
// html_reader jssil = new html_reader(deviceId, sId, swAfter, swcity);
// webView2.addJavascriptInterface(jssil, "HTMLOUT");
second_action = 1;
}
}
Hello Friends.
My codes are above. I want to run this command.
ndc = new taskResearch(userid, "1", "keyword", 5, 4, "orderid", 6, "title", "text");
When this command finished. I want this command to run.
Log.v("htmlg", "taskResearch finished");
But 2 of them start together and second one finishes firstly. I want that first command should start and finish then second command should start. How can i do that ?
What is my mistake ?
By the way, If you are fecthing html code from a website, you can use different structures.
You can use onPostExecute to detect process end.
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
processFinished();
}
void processFinished(){
Log.v("htmlg", "task_research finished");
}
One way to do it is override the onPostExecute method, as mentioned in another post. Another way to do it is as follows:
After you call ndc.execute() you can wait for it to get a result like this:
String output = ndc.get(); // i believe this is the api
Once you are returned that output, you can do whatever you want to it and the second log will print after.
Related
I am currently creating an app for a university project. Within the app I use two php scripts - one to set data from variables within the app to a MySQL data base, and the other to retrieve data from the database and set the variables within the app. The first script that sends the data to mySQL is working fine with no issues, however the script to retrieve the data from mySQL to set variables within the app is only working when ran through my webserver. When run within my app (on Activity Start and create) the variables are all set to zero. Any help would be amazing, Ive been stuck for weeks!
<?php
require "conn.php";
$username = "test";
$stmt = $conn->prepare("SELECT gold, goldMulti, xp, xpMulti, xpMax, xpMaxMulti, dmg, dmgMulti, bossCount, bossHp, bossHpMulti, level, backgroundCount FROM users WHERE username = '$username'");
$stmt ->execute();
$stmt ->bind_result($gold, $goldMulti, $xp, $xpMulti, $xpMax, $xpMaxMulti, $dmg, $dmgMulti, $bossCount, $bossHp, $bossHpMulti, $level, $backgroundCount);
$varaibles = array();
$stmt ->fetch();
$temp = array();
$temp['gold'] = $gold;
$temp['goldMulti'] = $goldMulti;
$temp['xp'] = $xp;
$temp['xpMulti'] = $xpMulti;
$temp['xpMax'] = $xpMax;
$temp['xpMaxMulti'] = $xpMaxMulti;
$temp['dmg'] = $dmg;
$temp['dmgMulti'] = $dmgMulti;
$temp['bossCount'] = $bossCount;
$temp['bossHp'] = $bossHp;
$temp['bossHpMulti'] = $bossHpMulti;
$temp['level'] = $level;
$temp['backgroundCount'] = $backgroundCount;
array_push($variables,$temp);
echo json_encode($temp);
?>
public class MainActivity extends AppCompatActivity {
// int variables for logic and functions ------------------------------------------------------
public int gold;
public int goldAwarded;
public int goldMultiplier;
public int xp;
public int xpAwarded;
public int xpMultiplier;
public int dmg;
public int dmgMultiplier;
public int bossCount;
public int bossHP;
public int bossHPMultiplier;
public int bossHPBase;
public int level;
public int xpMax;
public int bossCountFunc;
public int backgroundCount;
public int xpMaxMulti;
public int baseDmg;
// Widget variables -----------------------------------------------------------------------------
private TextView bossNumberText;
private TextView levelText;
private TextView goldText;
private TextView bossHealthText;
private ImageButton tapButton;
private ImageView bossImage;
private ImageView playerImage;
private ImageView bossImage2;
private ImageView bossImage3;
private ImageButton shopButton;
public String LoggedInUser = LogIn.getUser();
// Audio players --------------------------------------------------------------------------------
MediaPlayer mps;
MediaPlayer mpb;
MediaPlayer mpc;
MediaPlayer mpl;
MediaPlayer mpp;
// Websever php file URL to retrieve Data from user ----------------------------------------------
private static final String URL = "http://jg1104.brighton.domains/AppPhp/variablesretrieval.php";
private void getData(){
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONArray array = new JSONArray(response);
for(int i = 0; i<array.length(); i++){
JSONObject object = array.getJSONObject(i);
gold = object.getInt("gold");
goldMultiplier = object.getInt("goldMulti");
xp = object.getInt("xp");
xpMultiplier = object.getInt("xpMulti");
xpMax = object.getInt("xpMax");
xpMaxMulti = object.getInt("xpMaxMulti");
dmg = object.getInt("dmg");
dmgMultiplier = object.getInt("dmgMulti");
bossCount = object.getInt("bossCount");
bossHP = object.getInt("bossHp");
bossHPMultiplier = object.getInt("bossHpMulti");
level = object.getInt("level");
backgroundCount = object.getInt("backgroundCount");
}
}catch (Exception e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.toString(), Toast.LENGTH_SHORT).show();
}
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> param = new HashMap<>();
param.put("LoggedInUser", LoggedInUser);
return param;
}
}
);
Volley.newRequestQueue(MainActivity.this).add(stringRequest);
}
// On create -------------------------------------------------------------------------------------
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bossNumberText = (TextView) findViewById(R.id.bossNumberText);
levelText = (TextView) findViewById(R.id.levelText);
goldText = (TextView) findViewById(R.id.goldText);
bossHealthText = (TextView) findViewById(R.id.bossHealthText);
tapButton = (ImageButton) findViewById(R.id.TapButton);
bossImage = (ImageView) findViewById(R.id.bossImage);
playerImage = (ImageView) findViewById(R.id.playerImage);
bossImage2 = (ImageView) findViewById(R.id.bossImage2);
bossImage3 = (ImageView) findViewById(R.id.bossImage3);
shopButton = (ImageButton) findViewById(R.id.shopButton);
mpb = MediaPlayer.create(this, R.raw.backgroundmusic);
mpc = MediaPlayer.create(this, R.raw.coin);
mpl = MediaPlayer.create(this, R.raw.levelup);
mpp = MediaPlayer.create(this, R.raw.pain);
mps = MediaPlayer.create(this, R.raw.shootingsound);
// retrieving data from database and setting TextViews -----------------------------------
getData();
// Set looping and start of background music ---------------------------------------------
mpb.setLooping(true);
mpb.start();
// Initialising variable values on create ------------------------------------------------
goldAwarded = 100;
xpAwarded = 100;
baseDmg = 1;
bossHPBase = 10;
bossCountFunc = 1;
shopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchShop();
}
});
}
#Override
protected void onStart() {
// onclickListener for main button --------------------------------------------------------
super.onStart();
getData();
levelText.setText("Level: " + Integer.toString(level));
goldText.setText("Gold: " + Integer.toString(gold));
bossHealthText.setText("HP: " + Integer.toString(bossHP));
bossNumberText.setText("Boss: " + bossCount);
tapButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// shooting sound
mps.start();
// run method that looks to see if background needs to be changed
newBackground();
// handlers for enemy animations
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
bossImage.setImageDrawable(getResources().getDrawable(R.drawable.onezshot));
AnimationDrawable oneshotz = (AnimationDrawable) bossImage.getDrawable();
oneshotz.start();
}
}, 0);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
bossImage2.setImageDrawable(getResources().getDrawable(R.drawable.twozshot));
AnimationDrawable twozshot = (AnimationDrawable) bossImage2.getDrawable();
twozshot.start();
}
}, 0);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
bossImage3.setImageDrawable(getResources().getDrawable(R.drawable.threezshot));
AnimationDrawable threezshot = (AnimationDrawable) bossImage3.getDrawable();
threezshot.start();
}
}, 0);
// handler for shooting animation
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
playerImage.setImageDrawable(getResources().getDrawable(R.drawable.shooting));
AnimationDrawable shooting = (AnimationDrawable) playerImage.getDrawable();
shooting.start();
}
}, 0);
bossHP -= dmg;
bossHealthText.setText("HP: " + Integer.toString(bossHP));
// if boss dies
if (bossHP <= 1) {
mpp.start();
bossCount++;
bossCountFunc++;
backgroundCount++;
if (backgroundCount > 9) {
backgroundCount = 1;
}
if (bossCountFunc > 3) {
bossCountFunc = 1;
}
bossNumberText.setText("Boss: " + bossCount);
goldMultiplier++;
xpMultiplier++;
mpc.start();
gold += (goldAwarded * goldMultiplier);
goldText.setText("Gold: " + Integer.toString(gold));
xp += (xpAwarded * xpMultiplier);
bossHPMultiplier++;
// look for level up
if (xp >= xpMax) {
mpl.start();
level++;
dmgMultiplier++;
bossHPMultiplier *= 2;
dmg = (baseDmg * dmgMultiplier);
levelText.setText("lvl: " + Integer.toString(level));
xp = 0;
xpMax = xpMax * xpMaxMulti;
}
newBoss();
}
}
});
}
// Method to show or hide boss frames
public void newBoss(){
bossHP = bossHPBase * bossHPMultiplier;
if(bossCountFunc==1){
bossImage.setVisibility(View.VISIBLE);
bossImage2.setVisibility(View.INVISIBLE);
bossImage3.setVisibility(View.INVISIBLE);
}
if(bossCountFunc==2){
bossImage.setVisibility(View.INVISIBLE);
bossImage2.setVisibility(View.VISIBLE);
}
if(bossCountFunc==3){
bossImage2.setVisibility(View.INVISIBLE);
bossImage3.setVisibility(View.VISIBLE);
}
}
// method to check and change background
public void newBackground(){
ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.constraintLayout);
if(backgroundCount<=3){
layout.setBackgroundResource(R.drawable.main);
}
if(backgroundCount>3 && backgroundCount<=6){
layout.setBackgroundResource(R.drawable.maintwo);
}
if(backgroundCount>6 && backgroundCount<=9){
layout.setBackgroundResource(R.drawable.mainthree);
}
}
public void launchShop(){
Intent intent = new Intent(this, Shop.class);
startActivity(intent);
}
private void setData(final String LoggedInUser, final int gold,final int goldMultiplier,final int xp,final int xpMultiplier
,final int xpMax,final int xpMaxMulti,final int dmg
,final int dmgMultiplier,final int bossCount,final int bossHP
,final int bossHPMultiplier,final int level,final int backgroundCount){
final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(false);
progressDialog.setTitle("Setting Data");
progressDialog.show();
String uRl = "http://jg1104.brighton.domains/AppPhp/setdata.php";
StringRequest request = new StringRequest(Request.Method.POST, uRl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.equals("Data set")){
progressDialog.dismiss();
Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
}
else{
progressDialog.dismiss();
Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> param = new HashMap<>();
param.put("LoggedInUser", LoggedInUser);
param.put("gold", Integer.toString(gold));
param.put("goldMulti", Integer.toString(goldMultiplier));
param.put("xp", Integer.toString(xp));
param.put("xpMulti", Integer.toString(xpMultiplier));
param.put("xpMax", Integer.toString(xpMax));
param.put("xpMaxMulti", Integer.toString(xpMaxMulti));
param.put("dmg", Integer.toString(dmg));
param.put("dmgMulti", Integer.toString(dmgMultiplier));
param.put("bossCount", Integer.toString(bossCount));
param.put("bossHp", Integer.toString(bossHP));
param.put("bossHpMulti", Integer.toString(bossHPMultiplier));
param.put("level", Integer.toString(level));
param.put("backgroundCount", Integer.toString(backgroundCount));
return param;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(30000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getmInstance(MainActivity.this).addToRequestQueue(request);
}
#Override
protected void onStop() {
super.onStop();
setData(LoggedInUser,gold,goldMultiplier,xp,xpMultiplier,xpMax,xpMaxMulti,dmg,dmgMultiplier,bossCount,bossHP,bossHPMultiplier,level,backgroundCount);
}
}
Since the script is working when used in my webserver, I am sure it is something to do with my java coding.
This code is your problem:
try{
JSONArray array = new JSONArray(response);
for(int i = 0; i<array.length(); i++){
JSONObject object = array.getJSONObject(i);
gold = object.getInt("gold");
goldMultiplier = object.getInt("goldMulti");
xp = object.getInt("xp");
xpMultiplier = object.getInt("xpMulti");
xpMax = object.getInt("xpMax");
xpMaxMulti = object.getInt("xpMaxMulti");
dmg = object.getInt("dmg");
dmgMultiplier = object.getInt("dmgMulti");
bossCount = object.getInt("bossCount");
bossHP = object.getInt("bossHp");
bossHPMultiplier = object.getInt("bossHpMulti");
level = object.getInt("level");
backgroundCount = object.getInt("backgroundCount");
}
} catch (Exception e) {
}
You should not leave the catch block empty. It's likely throwing and swallowing an error.
Do this:
} catch (Exception e) {
Log.e("MyApp", "Error parsing!", e);
}
(Some reading on Logcat https://developer.android.com/studio/debug/am-logcat)
or get rid of the try catch all together and let your app crash (fail fast)!!
Your actual error (or first error I can see anyway) is that you are attempting to parse a JSONarray when your server side response is a JSONObject. This line of code:
JSONArray array = new JSONArray(response);
And this response:
{
"gold":600, "goldMulti":3,
"xp":0, "xpMulti":3, "xpMax":0, "xpMaxMulti":0,
"dmg":3,"dmgMulti":3,
"bossCount":3,
"bossHp":80,
"bossHpMulti":14,
"level":3,
"backgroundCount":3
}
(from here) http://jg1104.brighton.domains/AppPhp/variablesretrieval.php
You should parse it as a JsonObject or wrap your server side returned response in an Array [].
I'm working on app that will use biometric as an option to login. Before I use the actual biometric prompt I need to check one thing from server - I use AsyncTask to do it. So, to sum up - I invoke AsyncTask from Parent Activity (login.java), and then AsyncTask uses biometricUtils.java class, that makes biometric prompt. The point is, I keep passing null instead of context to biometricUtils.java:
Attempt to invoke virtual method 'java.util.concurrent.Executor android.content.Context.getMainExecutor()' on a null object reference at biometricUtils.<init>(biometricUtils.java:34)
I have no idea to pass the context correctly.
Here's my code:
login.java
public class login extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
Bundle bundle = getIntent().getExtras();
final boolean flag = false;
final String androidID = bundle.getString("androidID");
final Activity thisActivity = this;
final Context context = getApplicationContext();
// login using biometrics
Button btnBiometricLogin = findViewById(R.id.btnBiometricLogin);
btnBiometricLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAndroidID async = new checkAndroidID(context);
async.getParentActivity(thisActivity);
async.setFlag(flag);
async.execute(androidID);
}
});
}
}
checkAndroidID.java
public class checkAndroidID extends AsyncTask <String, Void, String> {
openHTTP openHTTP = new openHTTP();
requestHTTP requests = new requestHTTP();
Activity parentActivity;
private WeakReference<Context> contextRef;
Boolean flag;
public checkAndroidID(Context context){
contextRef = new WeakReference<>(context);
}
public void getParentActivity(Activity parentActivity){
this.parentActivity = parentActivity;
}
public void setFlag (Boolean flag){
this.flag = flag;
}
#Override
protected String doInBackground(String... strings) {
try {
HttpURLConnection httpConn = openHTTP.prepareConnection("url");
String json = "{ \"androidID\": \"" + strings[0] + "\" }";
requests.sendData(json, httpConn);
return requests.receiveData(httpConn);
} catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
String[] result = s.split(";");
Context ctx = contextRef.get();
if (result[0].equals("TRUE")) flag = true;
if (!flag) Toast.makeText(parentActivity, "Biometric authentication is now unavailable." +
" Please login using username and password", Toast.LENGTH_SHORT).show();
else {
biometricUtils biometrics = new biometricUtils(ctx);
biometrics.getParentActivity(parentActivity);
biometrics.getUsername(result[1]);
biometrics.inovkeBiometricPrompt();
}
super.onPostExecute(s);
}
}
and biometricUtlis.java
public class biometricUtils {
Activity parentActivity;
String username;
Context context;
public void getParentActivity(Activity parentActivity){
this.parentActivity = parentActivity;
}
public void getUsername(String s){
this.username = s;
}
public biometricUtils(Context context){
this.context = context;
}
// creating a variable for our Executor
Executor executor = ContextCompat.getMainExecutor(context); // LINE 34
// this will give us result of AUTHENTICATION
final BiometricPrompt biometricPrompt = new BiometricPrompt((FragmentActivity) parentActivity, executor, new BiometricPrompt.AuthenticationCallback() {
#Override
public void onAuthenticationError(int errorCode, #NonNull CharSequence errString) {
super.onAuthenticationError(errorCode, errString);
}
// THIS METHOD IS CALLED WHEN AUTHENTICATION IS SUCCESS
#Override
public void onAuthenticationSucceeded(#NonNull BiometricPrompt.AuthenticationResult result) {
super.onAuthenticationSucceeded(result);
Intent intent = new Intent(parentActivity.getApplicationContext(), tmp.class);
intent.putExtra("username", username);
parentActivity.startActivity(intent);
}
#Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed();
}
});
// creating a variable for our promptInfo
// BIOMETRIC DIALOG
final BiometricPrompt.PromptInfo promptInfo = new BiometricPrompt.PromptInfo.Builder().setTitle("Biometrical login")
.setDescription("Place your fingerprint on scanner to proceed").setNegativeButtonText("Cancel").build();
public void inovkeBiometricPrompt() {
biometricPrompt.authenticate(promptInfo);
}
}
I'm new to android studio and Java. My app uses jsoup to pass the contents of a website into an array where each element gets displayed on swipable flashcards (like tinder)
I've got a problem where my app crashes when I try to pass the result of the variable 'words' from onPostExecute() (line 123) to String num on line 49. I want to take the output of the function in onPostExcecute and set it as String num but I'm not sure how to do it.
public class AppHome extends AppCompatActivity implements PopupMenu.OnMenuItemClickListener {
TextView texx;
private ArrayList<String> al;
private ArrayAdapter<String> arrayAdapter;
private int i;
String words;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_home);
texx= findViewById(R.id.text1);
new doit().execute();
String num = words;
String str[] = num.split(",");
final ArrayList al = new ArrayList<String>(Arrays.asList(str));
arrayAdapter = new ArrayAdapter<>(this, R.layout.item, R.id.helloText, al );
SwipeFlingAdapterView flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
registerForContextMenu(flingContainer);
flingContainer.setAdapter(arrayAdapter);
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
al.remove(0);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
Toast.makeText(AppHome.this, "left", Toast.LENGTH_SHORT).show();
}
#Override
public void onRightCardExit(Object dataObject) {
Toast.makeText(AppHome.this, "right", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
al.add("XML ".concat(String.valueOf(i)));
arrayAdapter.notifyDataSetChanged();
Log.d("LIST", "notified");
i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
}
});
}
public class doit extends AsyncTask<Void,Void,Void> {
//String words;
#Override
protected Void doInBackground(Void... voids) {
try {
Document doc = Jsoup.connect("https://screenscrape4top40.000webhostapp.com/").get();
words=doc.text();
}catch(Exception e){e.printStackTrace();}
return null;
}
#Override
public void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
texx.setText(words);
//String str = (words);
//List<String> elephantList = Arrays.asList(str.split(","));
//texx.setText(elephantList.toString());
// texx.setText(elephantList);
}
}
}
public class doit extends AsyncTask<Void, Void, String> {
#Override
protected Void doInBackground(Void... voids) {
String words = "";
try {
Document doc = Jsoup.connect("https://screenscrape4top40.000webhostapp.com/").get();
words = doc.text();
} catch(Exception e) {
e.printStackTrace();
}
return words;
}
#Override
public void onPostExecute(String words) {
super.onPostExecute(aVoid);
texx.setText(words);
//String str = (words);
//List<String> elephantList = Arrays.asList(str.split(","));
//texx.setText(elephantList.toString());
// texx.setText(elephantList);
}
}
It should be fine now.
The problem is, you are not returning anything from the doInBackground method and hence you are not getting anything in the onPostExecute function.
You might consider checking the documentation for AsyncTask here.
In doInBackgroud() return the string(make sure it never beacome null) you want to use it on PostExecute()
also changed the data type of Parameter in onPostExecute method
onPostExecute(String Strs)
Then pass it to supper.OnPostExecute().
then u can use it.
The project im working on allow the user to register and login and all works perfectly until I spotted something wrong with the code. It doesn't count as an error because the compiler don't think its an error. Its just a bug or whatever people call it is. So here's what happened . The user login to their account, the database transfer their data into intent extras. then on the next activities, the username, coins and gems appears on top of the page so that the user know how much coins they have left. For testing purpose, i added add coin and decrease coin button. still, the code works perfectly. But after the user log out and relogin, the coins backs to the original amount. I know the problem caused by putting a value on the coin variable in User.java class. And still while logging in I put the default value of coins and gems for the user in the intent extras. I just cant find my way on how to put the value from database to the intent extras while user logging in.
so heres the code for login activity
buttonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Check user input is correct or not
if (validate()) {
//Get values from EditText fields
String Email = editTextEmail.getText().toString();
String Password = editTextPassword.getText().toString();
User player1 = new User(null, null, Email, Password);
//Authenticate user
User currentUser = myDb.Authenticate(player1);
//Check Authentication is successful or not
if (currentUser != null) {
System.out.println("Success");
Bundle extras = new Bundle();
extras.putString("P_ID", currentUser.getId());
extras.putString("P_NAME", currentUser.getName());
extras.putInt("P_COINS", currentUser.getCoins());
extras.putInt("P_GEMS", currentUser.getGems());
Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
intent.putExtras(extras);
startActivity(intent);
finish();
} else {
//User Logged in Failed
System.out.println("Failed");
}
}
}
});
the homeactivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set fullscreen and no title//////////
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
///////////////////////////////////////
setContentView(R.layout.home_screen);
myDb = new DatabaseHelper(this);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
pid = extras.getString("P_ID");
pname = extras.getString("P_NAME");
pcoins = extras.getInt("P_COINS");
pgems = extras.getInt("P_GEMS");
nametxt = (TextView)findViewById(R.id.playernametext);
coinstxt = (TextView)findViewById(R.id.playercoinstext);
gemstxt = (TextView)findViewById(R.id.playergemstext);
addcoin = (Button)findViewById(R.id.addbtn);
decoin = (Button)findViewById(R.id.decbtn);
nametxt.setText(" " +String.valueOf(pname) +" ");
coinstxt.setText(" Coins : " +String.valueOf(pcoins) +" ");
gemstxt.setText(" Gems : " +String.valueOf(pgems) +" ");
addcoin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pcoins += 10;
boolean isUpdate = myDb.updateUser(pid, pname, String.valueOf(pcoins), String.valueOf(pgems));
if (isUpdate == true) {
nametxt.setText(" " +String.valueOf(pname) +" ");
coinstxt.setText(" Coins : " +String.valueOf(pcoins) +" ");
gemstxt.setText(" Gems : " +String.valueOf(pgems) +" ");
}
}
});
decoin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pcoins -= 10;
boolean isUpdate = myDb.updateUser(pid, pname, String.valueOf(pcoins), String.valueOf(pgems));
if (isUpdate == true) {
nametxt.setText(" " +String.valueOf(pname) +" ");
coinstxt.setText(" Coins : " +String.valueOf(pcoins) +" ");
gemstxt.setText(" Gems : " +String.valueOf(pgems) +" ");
}
}
});
}
and of course the user class
public class User {
public String id;
public String userName;
public String email;
public String password;
public int coins = 1000;
public int gems = 10;
public User(String id, String userName, String email, String password) {
this.id = id;
this.userName = userName;
this.email = email;
this.password = password;
}
public String getId() {
return this.id;
}
public String getName() {
return this.userName;
}
public void addCoins(int addAmount) {
this.coins = addAmount;
}
public void decCoins(int decAmount) {
this.coins = decAmount;
}
public int getCoins() {
return this.coins;
}
public void addGems(int addAmount) {
this.gems = addAmount;
}
public void decGems(int decAmount) {
this.gems = decAmount;
}
public int getGems() {
return this.gems;
}
}
Honestly, my brain lacks of logic. Thats why i come here, to see whether my code does make sense.
And please, if you don't understand what i mean, just ask me which parts and please just dont immediately flag my question. Im really bad at english, trust me.
I'd suggest only passing the userid (which should never change) and then always getting the values coins etc from the database and also only changing them in the database (followed by resetting the displayed values from the values in the database).
You would then not have the issue of trying to juggle two sets of data you would then rely on the real data i.e. that in the database.
Working Example
The following is some code that goes through the basics.
When it starts the MainActivity, immediately starts the LoginActivity when you login then it takes you to the HomeActivity. This display the current Userid, Username, coins (initially 0) and gems.
There are 2 buttons Add10Coins and Add10gems clicking them will apply the new values to the DB displaying the updated values. If you stop the App and rerun, login then the values will be as they were.
Passing values wise, although the LoginActivity sets 3 Intent Extra values only one is used (the userid as a long) by the HomeActivity, but as per the values display all are accessible. If another activity is started then all you have to do is pass the userid via the intent.
The code isn't what I'd call complex but I'd certainly suggest going through it and try to understand it.
user.java
I've added some methods and also added some Constants, this is now :-
public class User {
public static final int ADJUSTTYPE_ADD = 1;
public static final int ADJUSTTYPE_REPLACE = 2;
public static final int ADJUSTTYPE_MULTIPLY = 3;
public static final int ADJUSTTYPE_DIVIDE = 4;
String id;
String userName;
String email;
String password;
int coins;
int gems;
public User(String id, String userName, String email, String password) {
this.id = id;
this.email = email;
//And so on. Don't mind this
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setName(String userName) {
this.userName = userName;
}
public String getName() {
return this.userName;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
public void setCoins(int coins) {
this.coins = coins;
}
public int getCoins() {
return this.coins;
}
public void setGems(int gems) {
this.gems = gems;
}
public int getGems() {
return this.gems;
}
public long getLongId() {
long id;
try {
id = Long.valueOf(this.id);
} catch (Exception e) {
return -1;
}
return id;
}
}
DatabaseHelper.java
This has been written from scratch based upon not the most stringent inspection of your code, it will largely be affected by my styling/usage techniques but not to the extent that I'd apply for real development.
Within this is the method adjustCoinsAndOrGems this is what is used to update the gems or coins in the DB and also in the returned User (so that a synchronised version of the User is returned, not that this returned use is used (I personally prefer to access the database as long as it's not an issue (e.g. noticeably affects performance)))
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mygame.db";
public static final int DBVERSION = 1;
public static final String TBL_USER = "user";
public static final String COL_USER_ID = BaseColumns._ID;
public static final String COL_USER_NAME = "user_name";
public static final String COL_USER_EMAIL = "user_email";
public static final String COL_USER_PASWWORD = "user_password";
public static final String COL_USER_COINS = "user_coins";
public static final String COL_USER_GEMS = "user_gems";
public static final String TBL_PLAYER = "player";
public static final String COL_PLYAER_ID = BaseColumns._ID;
public static final String COL_PLAYER_OWNINGUSER = "player_owninguser";
public static final String COL_PLAYER_NAME = "player_name";
//...... other columns
SQLiteDatabase mDB;
public DatabaseHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
String crt_tbl_user = "CREATE TABLE IF NOT EXISTS " + TBL_USER + "(" +
COL_USER_ID + " INTEGER PRIMARY KEY," +
COL_USER_NAME + " TEXT NOT NULL UNIQUE," +
COL_USER_EMAIL + " TEXT NOT NULL UNIQUE," +
COL_USER_PASWWORD + " TEXT NOT NULL," +
COL_USER_COINS + " INTEGER," +
COL_USER_GEMS + " INTEGER" +
")";
String crt_tbl_player = "CREATE TABLE IF NOT EXISTS " + TBL_PLAYER + "(" +
COL_PLYAER_ID + " INTEGER PRIMARY KEY," +
COL_PLAYER_NAME + " TEXT NOT NULL," +
COL_PLAYER_OWNINGUSER + " INTEGER REFERENCES " + TBL_USER + "(" + COL_USER_ID + ")" +
")";
db.execSQL(crt_tbl_user);
db.execSQL(crt_tbl_player);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
/*
Note core add but not intended to be used directly
Note this assumes that checks are done to ensure that name, email and password
have been provided
*/
private long addUser(Long id, String name, String email, String password, int coins, int gems) {
ContentValues cv = new ContentValues();
if (id > 0) {
cv.put(COL_USER_ID,id);
}
if (name.length() > 0) {
cv.put(COL_USER_NAME,name);
}
if (email.length() > 0 ) {
cv.put(COL_USER_EMAIL,email);
}
if (password.length() > 0) {
cv.put(COL_USER_PASWWORD,password);
}
cv.put(COL_USER_COINS,coins);
cv.put(COL_USER_GEMS,gems);
if (cv.size() < 1) return -1; //<<<<<<<<<< return if nothing to add
return mDB.insert(TBL_USER,null,cv);
}
/*
For add with just name, email and password (normal usage)
*/
public long addUser(String name, String email, String password) {
return this.addUser(-1L,name,email,password,0,0);
}
/*
For adding a user setting the coins and gems (special usage)
*/
public long addUserSettingCoinsAndGems(String name, String email, String password, int coins, int gems) {
return this.addUser(-1L,name,email,password,coins,gems);
}
public User getUser(long id) {
User rv = new User("-1","",",",""); // Invalid user
String whereclause = COL_USER_ID + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
Cursor csr = mDB.query(TBL_USER,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv.setId(String.valueOf(id));
rv.setName(csr.getString(csr.getColumnIndex(COL_USER_NAME)));
rv.setEmail(csr.getString(csr.getColumnIndex(COL_USER_EMAIL)));
rv.setPassword(csr.getString(csr.getColumnIndex(COL_USER_PASWWORD)));
rv.setCoins(csr.getInt(csr.getColumnIndex(COL_USER_COINS)));
rv.setGems(csr.getInt(csr.getColumnIndex(COL_USER_GEMS)));
}
csr.close();
return rv;
}
public User getUser(String userid) {
String whereclause = COL_USER_ID + "=?";
User rv = new User("-1","",",",""); // Invalid user
long id;
try {
id = Long.valueOf(userid);
} catch (Exception e) {
return rv;
}
String[] whereargs = new String[]{String.valueOf(id)};
Cursor csr = mDB.query(TBL_USER,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv.setId(String.valueOf(id));
rv.setName(csr.getString(csr.getColumnIndex(COL_USER_NAME)));
rv.setEmail(csr.getString(csr.getColumnIndex(COL_USER_EMAIL)));
rv.setPassword(csr.getString(csr.getColumnIndex(COL_USER_PASWWORD)));
rv.setCoins(csr.getInt(csr.getColumnIndex(COL_USER_COINS)));
rv.setGems(csr.getInt(csr.getColumnIndex(COL_USER_GEMS)));
}
csr.close();
return rv;
}
public User getUser(String email, String password) {
User rv = new User("-1","","","");
String whereclause = COL_USER_EMAIL + "=? AND " + COL_USER_PASWWORD + "=?";
String[] whereargs = new String[]{email,password};
Cursor csr = mDB.query(TBL_USER,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv.setId( String.valueOf(csr.getLong(csr.getColumnIndex(COL_USER_ID))));
rv.setName(csr.getString(csr.getColumnIndex(COL_USER_NAME)));
rv.setEmail(csr.getString(csr.getColumnIndex(COL_USER_EMAIL)));
rv.setPassword(csr.getString(csr.getColumnIndex(COL_USER_PASWWORD)));
rv.setCoins(csr.getInt(csr.getColumnIndex(COL_USER_COINS)));
rv.setGems(csr.getInt(csr.getColumnIndex(COL_USER_GEMS)));
}
csr.close();
return rv;
}
public User adjustCoinsAndOrGems(User u, int coins, int coin_adjustmode, int gems, int gem_adjustmode) {
ContentValues cv = new ContentValues();
User rv;
User user_fromDB = getUser(u.getId());
if (user_fromDB.id.equals("-1")) return u; // User not found so return
switch (coin_adjustmode) {
case User.ADJUSTTYPE_REPLACE:
cv.put(COL_USER_COINS,coins);
break;
case User.ADJUSTTYPE_ADD:
if (coins != 0) {
cv.put(COL_USER_COINS,user_fromDB.getCoins() + coins);
}
break;
case User.ADJUSTTYPE_MULTIPLY:
if (coins > 0) {
cv.put(COL_USER_COINS,user_fromDB.getCoins() * coins);
}
break;
case User.ADJUSTTYPE_DIVIDE:
if (coins > 0) {
cv.put(COL_USER_COINS,user_fromDB.getCoins() / coins);
}
break;
}
switch (gem_adjustmode) {
case User.ADJUSTTYPE_REPLACE:
cv.put(COL_USER_GEMS,gems);
break;
case User.ADJUSTTYPE_ADD:
if (gems != 0) {
cv.put(COL_USER_GEMS,user_fromDB.getGems() + gems);
}
break;
case User.ADJUSTTYPE_MULTIPLY:
if (gems > 0) {
cv.put(COL_USER_GEMS,user_fromDB.getGems() * gems);
}
break;
case User.ADJUSTTYPE_DIVIDE:
if (gems > 0) {
cv.put(COL_USER_GEMS,user_fromDB.getGems() / gems);
}
break;
}
if (cv.size() < 1) return u;
String whereclause = COL_USER_ID + "=?";
String[] whereargs = new String[]{u.getId()};
mDB.update(TBL_USER,cv,whereclause,whereargs);
return getUser(user_fromDB.getId());
}
public boolean authenticateUser(String email, String password) {
User u = getUser(email,password);
return (u.getLongId() > 0);
}
}
MainActivity.java
Very simple activity that starts the LoginActivity and when finally returned to does nothing (so you might as well kill the app).
public class MainActivity extends AppCompatActivity {
TextView mMessage;
DatabaseHelper mDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMessage = this.findViewById(R.id.message);
mDB = new DatabaseHelper(this);
addSomeTestingUsers();
// Immediately start Login Activity
Intent i = new Intent(MainActivity.this,LoginActivity.class);
startActivity(i);
}
#Override
protected void onResume() {
super.onResume();
mMessage.setText("Welcome back");
}
private void addSomeTestingUsers() {
if (DatabaseUtils.queryNumEntries(mDB.getWritableDatabase(),DatabaseHelper.TBL_USER) > 0) return;
mDB.addUser("Fred","fred#fredmal.com","password");
mDB.addUser("Mary","mary#mary.email.com","password");
}
}
LoginActivity
This is pretty straightforward note that as it stands you have to Login and that the emails and passwords for the 2 users are coded in the MainActivity. When supplied correctly the HomeActivivty is started :-
public class LoginActivity extends AppCompatActivity {
public static final String INTENTKEY_USERNAME = "IK_USERNAME";
public static final String INTENTKEY_USERID = "IK_USERID";
public static final String INTENTKEY_STRINGUSERID = "IK_USERIDSTRING";
Button mloginbtn;
EditText mEmail,mPassword;
Context mContext;
DatabaseHelper mDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mContext = this;
mloginbtn = this.findViewById(R.id.loginbtn);
mEmail = this.findViewById(R.id.email);
mPassword = this.findViewById(R.id.password);
mDB = new DatabaseHelper(this);
mloginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
handleAuthentication();
}
});
}
private void handleAuthentication() {
if (mDB.authenticateUser(mEmail.getText().toString(),mPassword.getText().toString())) {
User u = mDB.getUser(mEmail.getText().toString(),mPassword.getText().toString());
Intent i = new Intent(mContext,HomeActivity.class);
i.putExtra(INTENTKEY_USERNAME,u.getName());
i.putExtra(INTENTKEY_USERID,u.getLongId());
i.putExtra(INTENTKEY_STRINGUSERID,u.getId());
startActivity(i);
finish();
}
}
HomeActivity
For brevity, this has been used to display the coins and gems, it to is pretty basic and relies upon methods in the DatabaseHelper to do much of the work.
public class HomeActivity extends AppCompatActivity {
TextView mUserameTextView, mUseridTextView, mCoinsTextView, mGemsTextView;
Button mAdd10Coins, mAdd10Gems,mDone;
User mUser;
long mUserid;
Context mContext;
DatabaseHelper mDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mContext = this;
mDB = new DatabaseHelper(mContext);
mUserameTextView = this.findViewById(R.id.username);
mUseridTextView = this.findViewById(R.id.userid);
mCoinsTextView = this.findViewById(R.id.coins);
mGemsTextView = this.findViewById(R.id.gems);
Intent i = this.getIntent();
mUserid = i.getLongExtra(LoginActivity.INTENTKEY_USERID,-1);
mUser = mDB.getUser(mUserid);
refreshDisplay();
initButtons();
}
private void initButtons() {
mAdd10Coins = this.findViewById(R.id.add10coins);
mAdd10Coins.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDB.adjustCoinsAndOrGems(mUser,10,User.ADJUSTTYPE_ADD,0,User.ADJUSTTYPE_ADD);
mUser = mDB.getUser(mUserid);
refreshDisplay();
}
});
mAdd10Gems = this.findViewById(R.id.add10gems);
mAdd10Gems.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDB.adjustCoinsAndOrGems(mUser,0, User.ADJUSTTYPE_ADD,10,User.ADJUSTTYPE_ADD);
mUser = mDB.getUser(mUserid);
refreshDisplay();
}
});
mDone = this.findViewById(R.id.done);
mDB = new DatabaseHelper(mContext);
mDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
private void refreshDisplay() {
mUseridTextView.setText(mUser.getId());
mUserameTextView.setText(mUser.getName());
mCoinsTextView.setText(String.valueOf(mUser.getCoins()));
mGemsTextView.setText(String.valueOf(mUser.getGems()));
}
}
I'm trying to add a database connection inside my asynctask. This the code I'm working on:
DailySync.class:
DownloadSupplierMaster objAsyncTask;
// TODO get all checked items
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.daily_synchronize);
initControls();
objAsyncTask = new DownloadSupplierMaster(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.dailysync_menu, menu);
final MenuItem itemSync;
itemSync = menu.findItem(R.id.sync);
itemSync.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
StringBuffer responseText = new StringBuffer();
responseText.append("Selected modules are...\n");
ArrayList<SyncDataItems> itemList = dataAdapter.itemList;
for (int i = 0; i < itemList.size(); i++) {
SyncDataItems itemName = itemList.get(i);
if (itemName.isSelected()) {
responseText.append("\n" + itemName.getItem() );
}
}
objAsyncTask.execute();
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
public void onTaskComplete(String result) {
}
DownloadTask.class:
public class DownloadTask extends AsyncTask<Void, Void, Void> {
private Activity activity;
private AsyncTaskListener callback;
public DownloadSupplierMaster(Activity act) {
this.activity = act;
this.callback = (AsyncTaskListener)act;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(Void...params) {
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given website URL in JSONfunctions.class
String result = JSONFunctions.getJSONfromURL(URL);
try {
JSONArray jr = new JSONArray(result);
HashMap<String, String> map = new HashMap<String, String>();
String[] keys = { SupplierMaster.TAG_SUPPLIERCODE, SupplierMaster.TAG_SUPPLIERNAME,
SupplierMaster.TAG_SUPPLIERGROUP, SupplierMaster.TAG_SUPPLIERTYPE,
SupplierMaster.TAG_SUPPLIERADDRESS, SupplierMaster.TAG_SUPPLIERADDRESSALT, SupplierMaster.TAG_PHONE1,
SupplierMaster.TAG_PHONE2, SupplierMaster.TAG_FAX,
SupplierMaster.TAG_EMAIL, SupplierMaster.TAG_WEBSITE,
SupplierMaster.TAG_EXPENSEACCOUNT, SupplierMaster.TAG_CONTACTPERSON,
SupplierMaster.TAG_CREDITLIMIT, SupplierMaster.TAG_TOTALCREDIT, SupplierMaster.TAG_TIN,
SupplierMaster.TAG_TAXCODE, SupplierMaster.TAG_TERMS };
for(int i=0;i<jr.length();i++) {
jb = (JSONObject)jr.get(i);
for (String key : keys) {
map.put(key, jb.getString(key));
}
arraylist.add(map);
String suppliercode = jb.getString(SupplierMaster.TAG_SUPPLIERCODE);
String suppliername = jb.getString(SupplierMaster.TAG_SUPPLIERNAME);
String suppliergroup = jb.getString(SupplierMaster.TAG_SUPPLIERGROUP);
String suppliertype = jb.getString(SupplierMaster.TAG_SUPPLIERTYPE);
String supplieraddress = jb.getString(SupplierMaster.TAG_SUPPLIERADDRESS);
String supplieraddressalt = jb.getString(SupplierMaster.TAG_SUPPLIERADDRESSALT);
String phone1 = jb.getString(SupplierMaster.TAG_PHONE1);
String phone2 = jb.getString(SupplierMaster.TAG_PHONE2);
String fax = jb.getString(SupplierMaster.TAG_FAX);
String email = jb.getString(SupplierMaster.TAG_EMAIL);
String website = jb.getString(SupplierMaster.TAG_WEBSITE);
String expenseaccount = jb.getString(SupplierMaster.TAG_EXPENSEACCOUNT);
String contactperson = jb.getString(SupplierMaster.TAG_CONTACTPERSON);
String creditlimit = jb.getString(SupplierMaster.TAG_CREDITLIMIT);
String totalcredit = jb.getString(SupplierMaster.TAG_TOTALCREDIT);
String tin = jb.getString(SupplierMaster.TAG_TIN);
String taxcode = jb.getString(SupplierMaster.TAG_TAXCODE);
String terms = jb.getString(SupplierMaster.TAG_TERMS);
context.dbConnect(); // I'M GETTING A NULLPOINTEREXCEPTION IN THIS LINE!!!!!!!!!!!!
dbHelper.insertORReplaceToSUPPLIERCARD(suppliercode, suppliername, suppliergroup,
suppliertype, supplieraddress, supplieraddressalt, phone1,
phone2, fax, email, website, expenseaccount, contactperson,
creditlimit, totalcredit, tin, taxcode, terms);
dbHelper.close();
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
callback.onTaskComplete("Test");
}
AysncTaskListener.class:
public interface AsyncTaskListener {
public void onTaskComplete(String result);
}
The problem is, I'm getting a nullpointerexception in context.dbConnect();
What do you think is the problem? Any ideas? I would gladly appreciate your help. Thanks.
Where is this context object coming from? Can you confirm that it has a value?
From a design perspective, I suggest creating a database helper class that is a singleton, that you can then access from the AsyncTask and let it handle the database interactions for the whole application as this will both be easier to handle these sorts of exceptions as well as make it very easy to maintain all the database related code for your app.