带片段的getBaseContext()错误

时间:2014-08-08 03:16:52

标签: android sqlite

我基本上创建了ToDo列表。我正在处理数据库部分,因此用户可以键入项目,列表将在他们单击添加按钮时填充。现在,当我使用getBaseContext()

时,我一直遇到错误

我正在关注这个家伙的教程,而我正在使用片段我一直收到错误,我认为这是因为我正在使用片段

https://www.youtube.com/watch?v=ilpUe0Lkt8o

我在getBaseContext()

中遇到错误

这是我的FragmentTasks.Java

package com.example.navbar;

import android.content.Context;
import android.content.ContentValues;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


/**
 * A simple {@link Fragment} subclass.
 * 
 */
public class FragmentTasks extends ListFragment implements OnClickListener{

    public FragmentTasks() {
        // Required empty public constructor
    }
    EditText task;
    DataHandler handler;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view = inflater.inflate(R.layout.fragment_tasks, container, false);
        Button button = (Button)view.findViewById(R.id.button1);
        button.setOnClickListener(this);
        task = (EditText)view.findViewById(R.id.editText1);


        //return inflater.inflate(R.layout.fragment_tasks, container, false);
        /* button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Activity activity = getActivity();

                if (activity != null) {
                    Toast.makeText(activity, R.string.toast_you_just_clicked_a_fragment, Toast.LENGTH_LONG).show();
                }
            }

        });


        */

        return view;

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);

        ArrayAdapter adapter=ArrayAdapter.createFromResource(getActivity(), R.array.tasks, android.R.layout.simple_list_item_1);
        setListAdapter(adapter);
    }

    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l){
        Toast.makeText(getActivity(), "Item "+i,Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        String getTasks = task.getText().toString();
        handler = new DataHandler(getBaseContext()); **//Error is here!**
        handler.open();
        long id = handler.insertData(getTasks);
        Toast.makeText(getBaseContext(), "Data inserted", Toast.LENGTH_LONG).show(); **//And Here!**
        handler.close();


    }

}

onClick底部的右边是错误所在的位置。正上方^^^^^^

这是我的DataHandler.java

package com.example.navbar;
import java.sql.SQLException;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class DataHandler {
    public static final String TASKS = "tasks";
    public static final String TABLE_NAME = "my_table";
    public static final String DATA_BASE_NAME = "mydatabase";
    public static final int DATABASE_VERSION = 1;
    public static final String TABLE_CREATE = "create table mytable(tasks text not null);";

    DataBaseHelper dbhelper;
    Context ctx;
    SQLiteDatabase db;

    public DataHandler(Context ctx){
        this.ctx =ctx;
        dbhelper = new DataBaseHelper(ctx);

    }

    private static class DataBaseHelper extends SQLiteOpenHelper{

        public DataBaseHelper(Context ctx){
            super(ctx,DATA_BASE_NAME, null, DATABASE_VERSION);

        }


        @Override
        public void onCreate(SQLiteDatabase db){

            db.execSQL(TABLE_CREATE);
        }

        @Override
        public void onUpgrade (SQLiteDatabase db, int oldversion, int newVersion){

            db.execSQL("DROP TABLE IF EXISTS mytable");
            onCreate(db);

        }
    }

    public DataHandler open(){

        db = dbhelper.getWritableDatabase();
        return this;
    }

    public void close(){
        dbhelper.close();

    }

    public long insertData(String tasks){

        ContentValues content = new ContentValues();
        content.put(TASKS, tasks);
        return db.insertOrThrow(TABLE_NAME, null , content);

    }


    public Cursor returnData(){

        return db.query(TABLE_NAME, new String[] {TASKS}, null, null, null, null, null);
    }

}

2 个答案:

答案 0 :(得分:0)

尝试使用getActivity()而不是getBaseContext()。托管片段的活动充当片段的上下文。

这是官方的android开发人员指南,解释了如何在片段中获取上下文。

http://developer.android.com/guide/components/fragments.html

以下是相关段落

警告:如果片段中需要Context对象,则可以调用getActivity()。但是,只有在片段附加到活动时才要小心调用getActivity()。当片段尚未附加,或在其生命周期结束时被分离时,getActivity()将返回null。

基于上面的文档,我认为最终的问题是你正在实现onClickListener作为片段的方法,所以我不确定那时是否已经创建了活动。您可以尝试使用getApplicationContext()或perhap,更好的方法是将onclicklistener移动到onCreateView方法中。

即替换

button.setOnClickListener(this);

  button.setOnClickListener(new OnClickListener() { ... } );

答案 1 :(得分:0)

尝试使用v.getContext()

Toast.makeText(v.getContext(), "Data inserted", Toast.LENGTH_LONG).show();