I have an app, which consists of a tabhost. I am using a AsyncTask to perform some internet work in the background. Now in the onPostExecute, I want it to start a new activity. When I create a new intent, the new activity is shown, but there are no tabs.. it's just the activity.
Now i've read online how to do this, And i've managed to get into the right direction i think. This is the entire code:
package com.appsoweb.kvodeventer;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ActivityGroup;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class KVOMeldingen extends ActivityGroup {
public static final JSONObject jsonResult = null;
Button bLogin, bCreateAccount, bResetPassword;
EditText etUsername, etPassword;
static String Username;
static String Password;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.meldingen);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
Button bLogin = (Button) findViewById(R.id.bLogin);
Button bCreateAccount = (Button) findViewById(R.id.bCreateAccount);
Button bResetPassword = (Button) findViewById(R.id.bResetPassword);
bLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (etUsername.length() <= 0) {
etUsername.setError("Veld mag niet leeg zijn");
} else if (etPassword.length() <= 0) {
etPassword.setError("Veld mag niet leeg zijn");
} else {
Username = etUsername.getText().toString();
Password = etPassword.getText().toString();
}
LoginTask NDLT = new LoginTask();
NDLT.execute();
}
});
bCreateAccount.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Doe iets hier.......
}
});
bResetPassword.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Doe iets hier........
}
});
}
public static String getUsername() {
return Username;
}
public static String getPassword() {
return Password;
}
class LoginTask extends AsyncTask<Void, Void, JSONObject> {
ProgressDialog waitingDialog;
#Override
protected void onPreExecute() {
waitingDialog = new ProgressDialog(KVOMeldingen.this);
waitingDialog.setMessage("Laden...");
waitingDialog.show();
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(Void... params) {
JSONObject json = JsonFunctionLogin
.getJsonLoginResult("http://api.crossalertdeventer.nl/login.json");
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
super.onPostExecute(json);
if (waitingDialog.isShowing()) {
waitingDialog.dismiss();
Log.d("iets gebeurt", "gedaan");
}
try {
String LoginResult = json.getString("login");
String UserIdResult = json.getString("user_id");
Log.d("LoginResult", LoginResult);
Log.d("LoginUserId", UserIdResult);
json = null;
Intent intent = new Intent(KVOMeldingen.this, KVOCards.class);
View view = getLocalActivityManager().startActivity("KVOCards", intent
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
replaceView(view);
} catch (Exception e) {
Log.e("KVOMeldingen", "error" + e.getMessage());
}
}
public void replaceView(View v){
setContentView(v);
}
}
}
As you can see: I've created a View that will be shown trough an Intent. But the intent doesn't launch after the onbackground. It gives me an error:
Unable to start Activity componentInfo Unable to add window ... Token..... is not valid... Is your application running?
What am i doing wrong?
Thnx in advance
Starting a new Activity means you are navigating from your TabActivity to a normal Activity. Obviously you can't find a tab in Activity. You have to replace views instead of creating Activities.
Here is a good example of how to use ActivityGroup with TabActivity.
http://web.archive.org/web/20100816175634/http://blog.henriklarsentoft.com/2010/07/android-tabactivity-nested-activities/
But still this approach has been deprecated. You might have to consider using fragments though.
Take a look here, http://developer.android.com/resources/samples/Support4Demos/src/com/example/android/supportv4/app/FragmentTabs.html
Related
I'm trying to return an ArrayList from onPostExecute method of AsyncTask in Main Activity. I'm assigning returned ArrayList to the searchedText ArrayList of main activity. I'm not able to get elements of searchedText ArrayList in btnSearch onClickListener. Please let me know what is wrong in the code.
package com.example.dharak029.hw3_group09;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.InputStream;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
EditText textIn;
ImageButton buttonAdd;
LinearLayout container;
ArrayList<String> wordList;
byte[] buffer;
String text;
ArrayList<String> searchText;
ArrayList<String> searchedText;
int keywordCount=0;
void setResult(ArrayList<String> searchedText){
this.searchedText = searchedText;
Log.d("result",""+searchedText.size());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textIn = (EditText)findViewById(R.id.textin);
buttonAdd = (ImageButton)findViewById(R.id.add);
container = (LinearLayout)findViewById(R.id.container);
wordList = new ArrayList<String>();
searchText = new ArrayList<String>();
try {
InputStream is = getAssets().open("textfile.txt");
int size = is.available();
buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
int startIndex = 0;
for(int i=0;i<text.length()/30;i++){
searchText.add(text.substring(startIndex,startIndex+30));
startIndex = startIndex+30;
}
}
catch (Exception e){
}
findViewById(R.id.btnSearch).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(String word: wordList){
new DoWork(MainActivity.this).execute(word);
}
Intent intent = new Intent(MainActivity.this,WordsFound.class);
intent.putExtra("searchResults",searchedText);
startActivity(intent);
}
});
buttonAdd.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if (keywordCount <= 20) {
LayoutInflater layoutInflater =
(LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addView = layoutInflater.inflate(R.layout.row, null);
final TextView textOut = (TextView) addView.findViewById(R.id.textout);
textOut.setText(textIn.getText().toString());
wordList.add(textIn.getText().toString());
ImageButton buttonRemove = (ImageButton) addView.findViewById(R.id.remove);
final View.OnClickListener thisListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
((LinearLayout) addView.getParent()).removeView(addView);
wordList.remove(textOut.getText().toString());
listAllAddView();
keywordCount--;
}
};
buttonRemove.setOnClickListener(thisListener);
container.addView(addView);
listAllAddView();
keywordCount++;
}
}
});
}
private void listAllAddView(){
int childCount = container.getChildCount();
for(int i=0; i<childCount; i++){
View thisChild = container.getChildAt(i);
}
}
class DoWork extends AsyncTask<String,Integer,ArrayList<String>>{
ArrayList<String> searchResult = new ArrayList<String>();
ProgressBar progress;
MainActivity activity;
public DoWork(MainActivity activity) {
this.activity = activity;
}
#Override
protected ArrayList<String> doInBackground(String... params) {
for(int i=0;i<searchText.size();i++){
String text = searchText.get(i);
if(text.contains(params[0]))
searchResult.add(text);
}
Log.d("demo",""+searchResult.size());
return searchResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(ArrayList<String> aVoid) {
super.onPostExecute(aVoid);
activity.setResult(aVoid);
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
}
}
You can't put ArrayList in extras by putExtra() you have to use putStringArrayListExtra(). Try below code.
Intent intent = new Intent(MainActivity.this,WordsFound.class);
intent.putStringArrayListExtra("searchResults",searchedText);
startActivity(intent);
The problem is in the following code:
findViewById(R.id.btnSearch).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(String word: wordList){
new DoWork(MainActivity.this).execute(word);
}
Intent intent = new Intent(MainActivity.this, WordsFound.class);
intent.putExtra("searchResults",searchedText);
startActivity(intent);
}
});
Let's dissect the code. No problem with the following code. It's the usual code for click listener:
findViewById(R.id.btnSearch).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
}
Now, we look into the body code, from the following code:
for(String word: wordList){
new DoWork(MainActivity.this).execute(word);
}
We knew that DoWork is an AsyncTask which is doing an asynchronous process. So, the next code will be executed eventhough the DoWork haven't finished its process.
Let's see the next code:
Intent intent = new Intent(MainActivity.this, WordsFound.class);
intent.putExtra("searchResults", searchedText);
startActivity(intent);
Here you put the extra from searchedText variable which is only initialized in onCreate with:
searchText = new ArrayList<String>();
So, you'll always have the empty list when setting the extra.
To overcome the empty list issue, you need to send the extra only after the DoWork is finished doing its job. You can try calling the Intent inside the setResult
I created a Login Activity, it provides the login interface of the app.
public class LoginActivity extends Activity {
I extended the Activity class for it, and then overriden the onCreate method like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
this.username = (TextView) findViewById(R.id.loginUsername);
this.password = (TextView) findViewById(R.id.passwordLogin);
this.username.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
ImageView banner = (ImageView) findViewById(R.id.imageView5);
banner.setImageResource(R.drawable.banner);
}
Problem is.. nothing shows up on the simulator.
However this works perfectly fine:
MainActivity.getInstance().setContentView(R.layout.activity_login);
but is a very pad practice to use and will cause frequent crashes. What could be wrong? No console errors show.
LoginActivity class:
package flarehubpe.xflare.flarehub;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.text.InputType;
import android.widget.ImageView;
import android.widget.TextView;
import android.os.Bundle;
import flarehubpe.xflare.flarehub.utils.jsonData;
import org.json.JSONException;
public class LoginActivity extends Activity {
public TextView username;
public TextView password;
public boolean authenticated = false;
public ProfileActivity profileManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
this.username = (TextView) findViewById(R.id.loginUsername);
this.password = (TextView) findViewById(R.id.passwordLogin);
this.username.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
ImageView banner = (ImageView) findViewById(R.id.imageView5);
banner.setImageResource(R.drawable.banner);
}
public void spawnToDevice(){
}
public void login(){
try {
jsonData data = RestAPI.getResponse("http://xxx/login.php?username=" + this.username.getText().toString() + "&password=" + this.password.getText().toString());
if(data == null){
sendAlert("Error", "Something went wrong... This is embarrassing. Please contact # on twitter.","Ok");
return;
}
if(!data.getString("error").contains("false")){
sendAlert("Uh oh", data.getString("error"), "Ok");
return;
}
sendAlert("Success!", "You are now logged in.", "Ok");
createProfile(this.username.getText().toString(), this.password.getText().toString(), data.getInteger("coins"), data.getInteger("rankid"), data.getInteger("wins"), data.getInteger("kills"), data.getInteger("deaths"));
this.username.setText("");
this.password.setText("");
this.authenticated = true;
} catch (JSONException e) {
e.printStackTrace();
}
}
public void createProfile(String username, String password, Integer coins, Integer randid, Integer wins, Integer kills, Integer deaths){
this.profileManager = new ProfileActivity(username, password, coins, randid, wins, kills, deaths);
}
public void sendAlert(String title, String content, String buttonText) {
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle(title);
alertDialog.setMessage(content);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, buttonText,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
public void logout(){
this.authenticated = false;
this.spawnToDevice();
}
}
Maybe you use a wrong context for activity_login.xml
you should have the context of your activity :
tools:context=".package_name.LoginActivity"
I was learning to make a simple login app from youtube, however, when I build the code, although the app runs quite fine but it never assigns the value of 3 to the attempt counter later in the code, only the layout is visible and hence login doesn't work. Can you please help me? If you need any other file, write it in comment, I'll upload it later. Thanks.
package com.shubham.splashscreenemulation;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class UserLogin extends AppCompatActivity {
private static EditText username;
private static EditText password;
private static TextView attempts_left;
private static Button login_btn;
int attempt_counter = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
}
public void LoginButton(){
username = (EditText)findViewById(R.id.editText_user);
password = (EditText)findViewById(R.id.editText_password);
attempts_left = (TextView)findViewById(R.id.textView_attempt_count);
login_btn = (Button)findViewById(R.id.button_login);
attempts_left.setText(Integer.toString(attempt_counter));
login_btn.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
if(username.getText().toString().equals("Shubh") && password.getText().toString().equals("adidev"))
{
Toast.makeText(UserLogin.this, "Login credentials are correct!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.shubham.splashscreenemulation.SplashScreen");
startActivity(intent);
}
else
{
Toast.makeText(UserLogin.this, "Login credentials are not correct!", Toast.LENGTH_SHORT).show();
attempt_counter--;
attempts_left.setText(Integer.toString(attempt_counter));
if(attempt_counter == 0)
{
login_btn.setEnabled(false);
}
}
}
}
);
}
}
You don't call the function LoginButton() in your Activity.
Here some tips : function name starts with lowercase letter like loginButton ( with camelCase ), classes names starts with uppercase letter like AppCompatActivity. This tip is for more readability for the code. Why do you declare Views as static in that function?
package com.shubham.splashscreenemulation;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class UserLogin extends AppCompatActivity {
private static EditText username;
private static EditText password;
private static TextView attempts_left;
private static Button login_btn;
int attempt_counter = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
LoginButton();
}
public void LoginButton(){
username = (EditText)findViewById(R.id.editText_user);
password = (EditText)findViewById(R.id.editText_password);
attempts_left = (TextView)findViewById(R.id.textView_attempt_count);
login_btn = (Button)findViewById(R.id.button_login);
attempts_left.setText(Integer.toString(attempt_counter));
login_btn.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
if(username.getText().toString().equals("Shubh") && password.getText().toString().equals("adidev"))
{
Toast.makeText(UserLogin.this, "Login credentials are correct!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.shubham.splashscreenemulation.SplashScreen");
startActivity(intent);
}
else
{
Toast.makeText(UserLogin.this, "Login credentials are not correct!", Toast.LENGTH_SHORT).show();
attempt_counter--;
attempts_left.setText(Integer.toString(attempt_counter));
if(attempt_counter == 0)
{
login_btn.setEnabled(false);
}
}
}
}
);
}
You can add LoginButton() after setContentView or remove the LoginButton method, move everything inside onCreate.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
username = (EditText)findViewById(R.id.editText_user);
password = (EditText)findViewById(R.id.editText_password);
attempts_left = (TextView)findViewById(R.id.textView_attempt_count);
login_btn = (Button)findViewById(R.id.button_login);
attempts_left.setText(Integer.toString(attempt_counter));
login_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if(username.getText().toString().equals("Shubh") && password.getText().toString().equals("adidev"))
{
Toast.makeText(UserLogin.this, "Login credentials are correct!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.shubham.splashscreenemulation.SplashScreen");
startActivity(intent);
}
else
{
Toast.makeText(UserLogin.this, "Login credentials are not correct!", Toast.LENGTH_SHORT).show();
attempt_counter--; attempts_left.setText(Integer.toString(attempt_counter));
if(attempt_counter == 0)
{
login_btn.setEnabled(false);
}
}
}
});
}
You can also change your setText to this attempts_left.setText(attempt_counter+"");
this part of my code is having a problem
insertButton = (Button) findByViewId(R.id.button1);
insertButton.setOnClickListener(new OnClickListener();
it keeps saying method undefined for findByViewId, method for setOnClickListener not applicable and OnClickListener cannot be resolved
here is my full code
package edu.nyp.project;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AddData extends Activity {
Button insertButton = null;
EditText shopText= null;
EditText dealText= null;
EditText locationText= null;
EditText websiteText= null;
EditText categoryText= null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adddata);
insertButton = (Button) findByViewId(R.id.button1);
insertButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
DBAdapter dbAdapter = new
DBAdapter(getApplicationContext());
try{
dbAdapter.open();
String shop = shopText.getText().toString();
String deal = dealText.getText().toString();
String location = locationText.getText().toString();
String website = websiteText.getText().toString();
String category = categoryText.getText().toString();
}
catch(Exception e){
Log.d("Add Data ", e.getMessage());
}
finally{
if (dbAdapter != null)
dbAdapter.close();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.adddata, menu);
return true;
}
}
may i know what is wrong?
Import below line in your activity
import android.view.View.OnClickListener;
try
insertButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
}
}
Use findViewById method instead of findByViewId.
insertButton = (Button) findViewById(R.id.button1);
insertButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
//Code for action listener.
}
});
Only thing that i can find unusual about the above code is :
insertButton = (Button) findByViewId(R.id.button1);
So replace it with:
insertButton = (Button) findViewById(R.id.button1);
The rest of the code is fine. I mean the below code is perfectly fine:
insertButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
DBAdapter dbAdapter = new
DBAdapter(getApplicationContext());
try{
dbAdapter.open();
String shop = shopText.getText().toString();
String deal = dealText.getText().toString();
String location = locationText.getText().toString();
String website = websiteText.getText().toString();
String category = categoryText.getText().toString();
}
catch(Exception e){
Log.d("Add Data ", e.getMessage());
}
finally{
if (dbAdapter != null)
dbAdapter.close();
}
}
});
The above kind of syntax always works for me.
I try to start a new fragment from my fragmentActivity, but every time I try it, it comes up with a error, that tells me : Activity has been destroyed.
Source code from a tabController i've created:
package com.crosscommunications.kvodeventer;
import java.io.File;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
public class TabControllerMeldingen extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabcontroller);
final File f = new File("/data/data/com.crosscommunications.kvodeventer/files/data.txt");
if (f.exists()) {
System.out.println("File existed");
addFragment(new KVOCards(), false, FragmentTransaction.TRANSIT_NONE);
} else {
System.out.println("File not found!");
addFragment(new KVOMeldingen(), false, FragmentTransaction.TRANSIT_NONE);
}
}
public void addFragment(Fragment fragment, boolean addToBackStack, int transition) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.simple_fragment, fragment);
ft.setTransition(transition);
if (addToBackStack)
ft.addToBackStack(null);
ft.commit();
}
public void finishFragmentOrActivity(View v) {
FragmentManager manager = getSupportFragmentManager();
if (manager.getBackStackEntryCount() > 0)
getSupportFragmentManager().popBackStack();
else
finish();
}
public void launchNewFragment(View v) {
addFragment(new KVOOver(), true, FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
}
This code opens the KVOMeldingen class in most cases. So source of KVOMeldingen is:
package com.crosscommunications.kvodeventer;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class KVOMeldingen extends Fragment {
static String Username;
static String Password;
static String LoginResult;
static String LoginOk = "vet";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.kvomeldingen, container, false);
final EditText etUsername = (EditText) fragmentView.findViewById(R.id.etUsername);
final EditText etPassword = (EditText) fragmentView.findViewById(R.id.etPassword);
Button bLogin = (Button) fragmentView.findViewById(R.id.bLogin);
Button bCreateAccount = (Button) fragmentView.findViewById(R.id.bCreateAccount);
Button bResetPassword = (Button) fragmentView.findViewById(R.id.bResetPassword);
bLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (etUsername.length() <= 0) {
etUsername.setError("Veld mag niet leeg zijn");
} else if (etPassword.length() <= 0) {
etPassword.setError("Veld mag niet leeg zijn");
} else {
Username = etUsername.getText().toString();
Password = etPassword.getText().toString();
}
LoginTask NDLT = new LoginTask();
NDLT.execute();
}
});
bCreateAccount.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (etUsername.length() <= 0) {
etUsername.setError("Veld mag niet leeg zijn");
} else if (etPassword.length() <= 0) {
etPassword.setError("Veld mag niet leeg zijn");
} else {
Username = etUsername.getText().toString();
Password = etPassword.getText().toString();
}
RegisterTask RegTask = new RegisterTask();
RegTask.execute();
}
});
bResetPassword.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (etUsername.length() <= 0) {
etUsername.setError("Veld mag niet leeg zijn");
} else if (etPassword.length() <= 0) {
etPassword.setError("Veld mag niet leeg zijn");
} else {
Username = etUsername.getText().toString();
Password = etPassword.getText().toString();
}
ForgotTask forgTask = new ForgotTask();
forgTask.execute();
}
});
return fragmentView;
}
class LoginTask extends AsyncTask<Void, Void, JSONObject> {
ProgressDialog waitingDialog;
#Override
protected void onPreExecute() {
waitingDialog = new ProgressDialog(getActivity());
waitingDialog.setMessage("Laden...");
waitingDialog.show();
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(Void... params) {
JSONObject json = JsonFunctions
.getJsonLoginResult("http://api.crossalertdeventer.nl/login.json");
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
super.onPostExecute(json);
if (waitingDialog.isShowing()) {
waitingDialog.dismiss();
}
try {
LoginResult = json.getString("login");
Log.d("LoginResult", LoginResult);
if (LoginResult.equals("success")) {
WriteSettings(getActivity(), Username, Password,
"data.txt");
TabControllerMeldingen newFragment = new TabControllerMeldingen();
newFragment.addFragment(new KVOCards(), false, FragmentTransaction.TRANSIT_NONE);
} else if (LoginResult.equals("failed")) {
final AlertDialog alertDialog = new AlertDialog.Builder(
getActivity()).create();
alertDialog.setTitle("Fout");
alertDialog
.setMessage("Gebruikersnaam of wachtwoord incorrect");
alertDialog.setButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
} catch (Exception e) {
Log.e("KVOMeldingen", "error" + e.getMessage());
}
}
}
This source is actually bigger than this (i've cut it in half).
But you see in the AsyncTask, i try to call the method from the TabControllerMeldingen class to add a new fragment. When this method get's called, the app crashes
I've read on another thread on stackoverflow that it has to do something with the Super Oncreate method, but I can't figure out exactly what is going wrong.
Can anybody help me with this..? it's really important for me to understand this, because i believe fragments is the way to go basically these days.
You can't do this:
TabControllerMeldingen newFragment = new TabControllerMeldingen();
All activities have to be created through the framework. However, you are already inside one (you use the getActivity() method), so you need to do the same in this case. Get the activity and add the fragment on that.