mercredi 29 avril 2015

Android Studio: SQlite db ListView items disappear on startActivity

I am new to Android Studio and app creation. I followed Johhny Mansons Youtube quide for new apps, and extended the work greatly.

My problem is, logging out of the app removes items from the list view, upon a new login.

When I implemented login functionality, I changed LoginActivity to the main page, following a startActivity to reach MainActivity.java The app is fully functional once you log in. A can submit a picture and text, it is saved to SQLite and display in ListView tab.

However, whenever I log out, or tab back, and login again. The data is wiped. I believe it is because the startActivity executes MainActivity anew, which could be creating a new database and removing the old. But I am not quite sure of the cause and why it happens. Before implmeneting LoginActivity, the app would retain the data fine.

LoginActivity (Login page)

mLogin = (Button) findViewById(R.id.oButton);
    mLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            User user = new User(dbHandlerUsers.getUserCount(), String.valueOf(mUsername.getText()), String.valueOf(mPassword.getText()), null);
            if (validUser(user)) {

                CurrentUser g = CurrentUser.getInstance();
                g.setCurrentUser(String.valueOf(mUsername.getText()));

                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                return;
            }
            Toast.makeText(getApplicationContext(), "Wrong username or password", Toast.LENGTH_SHORT).show();
        }
    });

MainActivity (Function handling questions)

It is the populateList() that should get myListView to display Questions. It might also be worth noting that I am using two databases, one for users and one for questions.

public class MainActivity extends ActionBarActivity {

private static final int EDIT = 0, DELETE = 1;

EditText questionTxt; //include picture too
ImageView questionImageImgView;
List<Question> Questions = new ArrayList<Question>();
List<Question> OtherQuestions = new ArrayList<Question>(); //Preparing for incoming data
ListView myListView;
ListView otherListView;
Uri imageUri = Uri.parse("android.http://ift.tt/1PXK2zr"+R.drawable.no_user_logo);
DatabaseHandler dbHandler;
double myLongitude = 0.0d, myLatitude = 0.0d; //Later remove 0.0d
double qLongitude = 0.0d, qLatitude = 0.0d;
int longClickedItemIndex;
ArrayAdapter<Question> questionAdapter;

private float currentValue;
private long lastUpdate;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    dbHandler = new DatabaseHandler(getApplicationContext());

    questionTxt = (EditText) findViewById(R.id.txtQuestion);
    myListView = (ListView) findViewById(R.id.listView);
    otherListView = (ListView) findViewById(R.id.listView2);
    questionImageImgView = (ImageView) findViewById(R.id.imgQuestion);

    //This make our items in listView clickable on an event.
    registerForContextMenu(myListView);
    myListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            longClickedItemIndex = position; //Position tell where the item was clicked

            return false;
        }
    });

    TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
    tabHost.setup();
    ...


    final Button addBtn = (Button) findViewById(R.id.btnAdd);
    addBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Find the currently logged in user
            CurrentUser user = CurrentUser.getInstance();
            String currentUser=user.getCurrentUser();

            //Add question
            Question question = new Question(dbHandler.getQuestionsCount(), String.valueOf(questionTxt.getText()), qLongitude, qLatitude, imageUri, currentUser);
            dbHandler.createQuestion(question);
            Questions.add(question);
            questionAdapter.notifyDataSetChanged();
            Toast.makeText(getApplicationContext(), String.valueOf(questionTxt.getText()) + " has been added", Toast.LENGTH_SHORT).show();
            clearFields();
        }
    });

    questionTxt.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            addBtn.setEnabled(String.valueOf(questionTxt.getText()).trim().length() > 0);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });




    //Populate list view with questions
    if (dbHandler.getQuestionsCount() !=0)  //If there are contacts
        Questions.addAll(dbHandler.getAllQuestions()); //Add content

    populateList();

}

...

    dHandler.deleteQuestion(Questions.get(longClickedItemIndex));
            Questions.remove(longClickedItemIndex);
            questionAdapter.notifyDataSetChanged();
            break;
    }

    return super.onContextItemSelected(item);
}

public void onActivityResult(int reqCode, int resCode, Intent data) {
    if (resCode == RESULT_OK) {
        if (reqCode == 1) {
            imageUri = data.getData();
            questionImageImgView.setImageURI(data.getData());

        }
    }
}

private void populateList() {
    questionAdapter = new QuestionListAdapter();
    myListView.setAdapter(questionAdapter);
    //Add method to search for other phone's adapter list
    otherListView.setAdapter(questionAdapter);
}

private class QuestionListAdapter extends ArrayAdapter<Question> { //THIS CREATES A GROUP OF QUESTION, DISTANCE AND IMAGE - AS ONE OBJECT
    public QuestionListAdapter() {
        super (MainActivity.this, R.layout.listview_item, Questions);
    }
    @Override
    public View getView(int position, View view, ViewGroup parent) {
        if (view == null)
            view = getLayoutInflater().inflate(R.layout.listview_item, parent, false);

        Question currentQuestion = Questions.get(position);

        TextView question = (TextView) view.findViewById(R.id.qQuestion);
        question.setText(currentQuestion.getQuestion());
        TextView username = (TextView) view.findViewById(R.id.qLongitude);
        username.setText(currentQuestion.getUser());
        //TextView longitude = (TextView) view.findViewById(R.id.qLongitude);
        //longitude.setText(currentQuestion.getUser());
        TextView latitude = (TextView) view.findViewById(R.id.qLatitude);
        latitude.setText(Double.toString(currentQuestion.getLatitude()) + " meters");
        ImageView  questionImage = (ImageView) view.findViewById(R.id.qImageView);
        questionImage.setImageURI(currentQuestion.getImageURI());

        //TextView distance = (TextView) view.findViewById(R.id.qDistance);
        //distance.setText(Double.toString(currentQuestion.getDistance()));

        return view;
    }
}

Let me know if I should provide more information.

Class overview - CurrentUser - DatabaseHandler - DatabaseHandlerUser - LoginActivity
- MainActivity
- Question
- RegisterActivity - User

Aucun commentaire:

Enregistrer un commentaire