字符串在插入数据库时转换得很奇怪

huangapple go评论88阅读模式
英文:

Strings converting oddly when inserted into database

问题

我是一名学生,正在进行我的第一个Android Studio项目。我尝试搜索这个问题,但搜索结果中大多是与日期格式化相关的内容,我相当确定这不是问题所在。

我创建了一个带有整数和三个String参数的对象。其中两个字符串是从Date对象转换而来的。一切看起来都很顺利,直到我调用DAO将其插入数据库。的确进行了插入,但是转换后的两个日期字符串不再是字符串。有人能告诉我为什么会发生这种情况,以及我如何阻止它发生?以下是我猜测需要的代码:

@Override
protected Void doInBackground(final Void... params) {
	
	mTermDao.deleteAllTerms();
	
	Calendar calobj = Calendar.getInstance();
	calobj.add(Calendar.MONTH, -3);
	calobj.add(Calendar.DATE, -3);
	Date notToday = calobj.getTime();
	calobj.add(Calendar.MONTH, 6);
	Date next = calobj.getTime();
	DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	String strDateOne = dateFormat.format(notToday);
	String strDateTwo = dateFormat.format(next);
	String termTitle = "Term 1";

	TermEntity termEntity= new TermEntity(1,termTitle, strDateOne, strDateTwo);
	mTermDao.insert(termEntity);

	return null;
}

DAO部分如下:

@Dao
public interface TermDAO {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insert(TermEntity termEntity);
}

ViewModel部分如下:

public class TermViewModel extends AndroidViewModel {
    private ScheduleRepository mRepository;
    private LiveData<List<TermEntity>> mAllTerms;
    
    public TermViewModel(Application application){
        super(application);
        mRepository = new ScheduleRepository(application);
        mAllTerms = mRepository.getAllTerms();
    }
    
    public LiveData<List<TermEntity>> getAllTerms(){
        return mAllTerms;
    }
    
    public void insert(TermEntity termEntity){
        mRepository.insert(termEntity);
    }
    
    public void delete(TermEntity termEntity){
        mRepository.delete(termEntity);
    }
    
    public int lastID(){
        return mAllTerms.getValue().size();
    }
}

TermEntity部分如下:

@Entity(tableName="term_table")
public class TermEntity {

    @PrimaryKey
    private int termId;
    private String termTitle;
    private String termStart;
    private String termEnd;

    public TermEntity(int termId, String termTitle, String termStart, String termEnd) {
        this.termId = termId;
        this.termTitle = termTitle;
        this.termStart = termStart;
        this.termEnd = termEnd;
    }

    // ... 其他方法 ...
}

TermAdapter部分如下:

public class TermAdapter extends RecyclerView.Adapter<TermAdapter.TermViewHolder> {
    // ... 其他部分 ...

    class TermViewHolder extends RecyclerView.ViewHolder {
        // ... 其他部分 ...

        private TermViewHolder(View itemView) {
            super(itemView);
            
            // ... 其他部分 ...
        }
    }
}

从接收Intent的Activity部分如下:

if (getIntent().getStringExtra("termTitle") != null) {
    String start = getIntent().getStringExtra("termStart");
    nameView.setText(getIntent().getStringExtra("termTitle"));
    startView.setText(start);
    endView.setText(getIntent().getStringExtra("termEnd"));
}

虽然它确实创建了一个对象并将其插入到数据库中,但稍后当我使用获取器函数来填充一个textView时,开始和结束的字符串会显示为空。程序没有出错,字段只是显示为空白。

我应该补充说明,我的理论是基于在第一个代码块的最后两行上运行调试并设置断点。在这一行:

TermEntity termEntity= new TermEntity(1,termTitle, strDateOne, strDateTwo);

我的IDE显示了strDateOne和strDateTwo的值是字符串。
但是,当运行下一行时,它们不再像'Term 1'一样被单引号包围,而是没有引号。

英文:

I'm a student working on my first Android Studio project. My attempts to search for this problem have led to a lot of date formatting results which I'm reasonably sure is not the problem.

I create an object with an int and three String parameters. Two of the strings are converted from Date object. It all seems to be going well until I call the DAO to insert it into the database. It does insert, but the two converted-date strings are no longer strings. Can someone tell me why this is happening and how I can make it stop? My best guesses at the needed code below:

@Override
protected Void doInBackground(final Void... params) {
	
	mTermDao.deleteAllTerms();
	
	Calendar calobj = Calendar.getInstance();
	calobj.add(Calendar.MONTH, -3);
	calobj.add(Calendar.DATE, -3);
	Date notToday = calobj.getTime();
	calobj.add(Calendar.MONTH, 6);
	Date next = calobj.getTime();
	DateFormat dateFormat = new SimpleDateFormat(&quot;yyyy-mm-dd hh:mm:ss&quot;);
	String strDateOne = dateFormat.format(notToday);
	String strDateTwo = dateFormat.format(next);
	String termTitle = &quot;Term 1&quot;;

	TermEntity termEntity= new TermEntity(1,termTitle, strDateOne, strDateTwo);
	mTermDao.insert(termEntity);

	return null;
}

And the Dao

@Dao
public interface TermDAO {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insert(TermEntity termEntity);
}

ViewModel

public class TermViewModel extends AndroidViewModel {
    private ScheduleRepository mRepository;
    private LiveData&lt;List&lt;TermEntity&gt;&gt; mAllTerms;
    public TermViewModel(Application application){
        super(application);
        mRepository=new ScheduleRepository(application);
        mAllTerms =mRepository.getAllTerms();
    }
    public LiveData&lt;List&lt;TermEntity&gt;&gt; getAllTerms(){
        return mAllTerms;
    }
    public void insert(TermEntity termEntity){
        mRepository.insert(termEntity);
    }
    public void delete(TermEntity termEntity){
        mRepository.delete(termEntity);
    }
    public int lastID(){
        return mAllTerms.getValue().size();
    }
}

The TermEntity

@Entity(tableName=&quot;term_table&quot;)
public class TermEntity {

    @PrimaryKey
    private int termId;
    private String termTitle;
    private String termStart;
    private String termEnd;

    public TermEntity(int termId, String termTitle, String termStart, String termEnd) {
        this.termId = termId;
        this.termTitle = termTitle;
        this.termStart = termStart;
        this.termEnd = termEnd;
    }

    @Override
    public String toString() {
        return &quot;TermEntity{&quot; +
                &quot;termId=&quot; + termId +
                &quot;, termTitle=&#39;&quot; + termTitle + &#39;\&#39;&#39; +
                &quot;, termStart=&quot; + termStart +
                &quot;, termEnd=&quot; + termEnd +
                &#39;}&#39;;
    }

    public int getTermId() {
        return termId;
    }

    public void setTermId(int termId) {
        this.termId = termId;
    }

    public String getTermTitle() {
        return termTitle;
    }

    public void setTermTitle(String termTitle) {
        this.termTitle = termTitle;
    }

    public String getTermStart() {
        return termStart;
    }

    public void setTermStart(String termStart) {
        this.termStart = termStart;
    }

    public String getTermEnd() {
        return termEnd;
    }

    public void setTermEnd(String termEnd) {
        this.termEnd = termEnd;
    }
}

TermAdapter where the object is accessed.

public class TermAdapter extends RecyclerView.Adapter&lt;TermAdapter.TermViewHolder&gt; {

    class TermViewHolder extends RecyclerView.ViewHolder {
        private final TextView termItemView;


        private TermViewHolder(View itemView) {
            super(itemView);
            termItemView = itemView.findViewById(R.id.termTextView);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = getAdapterPosition();
                    final TermEntity current = mTerms.get(position);
                    Intent intent = new Intent(context, TermDetailsActivity.class);
                    intent.putExtra(&quot;termTitle&quot;, current.getTermTitle());
                    intent.putExtra(&quot;startTerm&quot;, current.getTermStart());
                    intent.putExtra(&quot;endTerm&quot;, current.getTermEnd());
                    intent.putExtra(&quot;termId&quot;, current.getTermId());
                    intent.putExtra(&quot;position&quot;,position);
                    context.startActivity(intent);
                }
            });
        }
    }

From the Activity where the intent is picked up

        if(getIntent().getStringExtra(&quot;termTitle&quot;)!=null) {
            String start = getIntent().getStringExtra(&quot;termStart&quot;);
            nameView.setText(getIntent().getStringExtra(&quot;termTitle&quot;));
            startView.setText(start);
            endView.setText(getIntent().getStringExtra(&quot;termEnd&quot;));
        } 

It does create an object and inserts into the database, but later when I use the getter function for the start and end strings to populate a textView, they show up as null. The program doesn't error, the fields just appear blank.

I should add my theory is based on running debug w/breakpoints on the last two lines of the first code block. On this line:
TermEntity termEntity= new TermEntity(1,termTitle, strDateOne, strDateTwo);
my IDE showed the values for strDateOne and strDateTwo as strings.
When it ran the next line however, instead of being surrounded by single quotes like 'Term 1', they did not have quotes.

答案1

得分: 1

你只是使用了错误的意图包名称。"startTerm","termStart",以及后面的结束部分。

为了避免这种情况,在发送活动中使用常量字符串 INTENT_CONST,然后在接收活动中像这样使用它:intent.getExtras(SendingActivity.INTENT_CONST, value);

英文:

You just use wrong intent bundle names. "startTerm", "termStart" and for end so on

To avoid this use constant string INTENT_CONST in sending activity and use it from a recieving activity like intent.getExtras(SendingActivity.INTENT_CONST, value);

huangapple
  • 本文由 发表于 2020年5月5日 02:48:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/61599441.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定