首页 \ 问答 \ Android Studio:SQlite db ListView项目在startActivity上消失(Android Studio: SQlite db ListView items disappear on startActivity)

Android Studio:SQlite db ListView项目在startActivity上消失(Android Studio: SQlite db ListView items disappear on startActivity)

我是Android Studio和应用创建的新手。 我跟随Johhny Mansons Youtube quide寻找新的应用程序,并大大扩展了工作。

我的问题是,退出应用程序会在新登录时从列表视图中删除项目。

当我实现登录功能时,我将LoginActivity更改为主页面,按照startActivity到达MainActivity.java登录后应用程序功能齐全.A可以提交图片和文本,保存到SQLite并显示在ListView选项卡中。

但是,每当我退出或退回,然后再次登录。 数据被擦除。 我相信这是因为startActivity重新执行MainActivity,这可能是创建一个新数据库并删除旧数据库。 但我不确定原因及其发生的原因。 在实现LoginActivity之前,应用程序会保留数据。

LoginActivity(登录页面)

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(功能处理问题)

populateList()应该让myListView显示问题。 值得注意的是,我正在使用两个数据库,一个用于用户,一个用于提问。

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.resource://kaist624.projekt.kse624_projekt1"+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;
    }
}

如果我应该提供更多信息,请告诉我。

类概述 - CurrentUser - DatabaseHandler - DatabaseHandlerUser - LoginActivity
- 主要活动
- 题
- RegisterActivity - 用户


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.resource://kaist624.projekt.kse624_projekt1"+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


原文:https://stackoverflow.com/questions/29945756
更新时间:2023-04-13 11:04

最满意答案

创建一个表单 ,每个图像都有一个复选框。

使用图片ID作为复选框的ID。

如果表单已提交且有效,则会对图像进行迭代以了解其复选框是否已选中:

use Symfony\Component\HttpFoundation\Request;

use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

public function deleteImagesAction(Request $request){

    // ...

    $images = // ...

    $formBuilder = $this->createFormBuilder();

    foreach($images as $image){
        $formBuilder->add($image->getId(),CheckboxType::class,array('label'=>$image->getName(),'required'=>false));
    }

    $formBuilder->add('submit',SubmitType::class);

    $form = $formBuilder->getForm();

    $form->handleRequest($request);

    if($form->isValid()){
        $data = $form->getData();

        $em = $this->getDoctrine()->getEntityManager();

        foreach($images as $image){
            if($data[$image->getId()]){
                $em->remove($image);
            }
        }

        $em->flush();

        return $this->redirectToRoute(...);
    }

    return $this->render(...);
}

Create a Form, with a checkbox for each image.

Use the image id as id for the checkbox.

If the form is submitted and valid iterate over the images to know if their checkboxes were checked or not :

use Symfony\Component\HttpFoundation\Request;

use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

public function deleteImagesAction(Request $request){

    // ...

    $images = // ...

    $formBuilder = $this->createFormBuilder();

    foreach($images as $image){
        $formBuilder->add($image->getId(),CheckboxType::class,array('label'=>$image->getName(),'required'=>false));
    }

    $formBuilder->add('submit',SubmitType::class);

    $form = $formBuilder->getForm();

    $form->handleRequest($request);

    if($form->isValid()){
        $data = $form->getData();

        $em = $this->getDoctrine()->getEntityManager();

        foreach($images as $image){
            if($data[$image->getId()]){
                $em->remove($image);
            }
        }

        $em->flush();

        return $this->redirectToRoute(...);
    }

    return $this->render(...);
}

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)