簡體   English   中英

如何使用 layoutinflater 和 viewgroup 從 sqliteopenhelper 類更改線性布局背景

[英]How to change linearlayout background from sqliteopenhelper class using layoutinflater and viewgroup

我試過任何方法

這是我的DBController.java

public class DBController  extends SQLiteOpenHelper
{  
    public DBController(Context applicationcontext) 
    {
        super(applicationcontext, "user.db", null, 1);
    }

    //Creates Table
    @Override
    public void onCreate(SQLiteDatabase database) 
    {
        String query;
        query = "CREATE TABLE users ( userId INTEGER, userName TEXT)";
        database.execSQL(query);
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, int version_old, int current_version) 
    {
        String query;
        query = "DROP TABLE IF EXISTS users";
        database.execSQL(query);
        onCreate(database);
    }


    /**
     * Inserts User into SQLite DB
     * @param queryValues
     */
    public void insertUser(HashMap<String, String> queryValues) 
    {
        SQLiteDatabase database = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("userId", queryValues.get("userId"));
        values.put("userName", queryValues.get("userName"));
        database.insert("users", null, values);
        database.close();
    }


    /**
     * Get list of Users from SQLite DB as Array List
     * @return
     */

    public ArrayList<HashMap<String, String>> getAllUsers() 
    {
        ArrayList<HashMap<String, String>> usersList;
        usersList = new ArrayList<HashMap<String, String>>();
        String selectQuery = "SELECT  * FROM users";
        SQLiteDatabase database = this.getWritableDatabase();
        Cursor cursor = database.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) 
        {
            do 
            {
                HashMap<String, String> map = new HashMap<String, String>();

                String idnya = cursor.getString(0);
                if (idnya.equals("36"))
                {
                    map.put("userId", "My Id");
                    map.put("userName", "My Username");

                    Context context=null;
                    ViewGroup parent=null;
                    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);               
                    View v = inflater.inflate(R.layout.view_user_entry, parent, true);
                    LinearLayout bg = (LinearLayout) v.findViewById(R.id.wrapper);
                    bg.setBackgroundResource(R.drawable.bubble_yellow);
                }
                else
                {
                    map.put("userId", cursor.getString(0));
                    map.put("userName", cursor.getString(1));
                }
                usersList.add(map);
            } 
            while (cursor.moveToNext());
        }
        database.close();
        return usersList;       
    }


}

這是MainActivity.java

public class MainActivity extends ActionBarActivity 
{
    DBController controller = new DBController(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Get User records from SQLite DB
        ArrayList<HashMap<String, String>> userList = controller.getAllUsers();
        // If users exists in SQLite DB
        if (userList.size() != 0) 
        {           
            ListAdapter adapter = new SimpleAdapter(MainActivity.this, userList, R.layout.view_user_entry, new String[] {
                            "userId", "userName" }, new int[] { R.id.userId, R.id.userName });
            ListView myList = (ListView) findViewById(android.R.id.list);
            myList.setAdapter(adapter); 
        }

        Intent alarmIntent = new Intent(getApplicationContext(), SampleBC.class);
        // Pending Intent Object
        PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        // Alarm Manager calls BroadCast for every Ten seconds (10 * 1000), BroadCase further calls service to check if new records are inserted in 
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + 5000, 10 * 1000, pendingIntent);
    }


    // Options Menu (ActionBar Menu)
    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    // When Options Menu is selected
    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
        // Handle action bar item clicks here. 
        int id = item.getItemId();
        // When Sync action button is clicked
        if (id == R.id.action_settings) 
        {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


}

這是view-user_entry.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:id="@+id/wrapper"
    android:background="@drawable/bubble_green" >

       <TextView
           android:id="@+id/userName"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_marginBottom="5dp"
           android:layout_marginTop="dp"
           android:paddingLeft="0dip"
           android:paddingTop="0dip"
           android:textColor="@android:color/primary_text_light"
           android:textSize="14sp"          
            />

       <TextView
        android:id="@+id/userId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

這是我的錯誤

                    Context context=null;
                    ViewGroup parent=null;
                    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);               
                    View v = inflater.inflate(R.layout.view_user_entry, parent, true);
                    LinearLayout bg = (LinearLayout) v.findViewById(R.id.wrapper);
                    bg.setBackgroundResource(R.drawable.bubble_yellow);

當我運行應用程序時,它說強制關閉。 我不知道我該怎么辦,因為所有方法都試過了,但仍然強制關閉。

非常感謝。

第一步將你的名字“layaout_first”保存在你的sqlite中,你需要使用你的方法,最后也是重要的:getResources().getIdentifier(id, "layaout_first", ctx.getPackageName());,並以編程方式改變你的背景

您嘗試從 Null context獲取LayoutInflater 你應該使用全局上下文:

if (idnya.equals("36"))
            {
                map.put("userId", "My Id");
                map.put("userName", "My Username");

                Context context=null;//here context is null removae this line
                ViewGroup parent=null;
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);               
                View v = inflater.inflate(R.layout.view_user_entry, parent, true);
                LinearLayout bg = (LinearLayout) v.findViewById(R.id.wrapper);
                bg.setBackgroundResource(R.drawable.bubble_yellow);
            }
            else
            {
                map.put("userId", cursor.getString(0));
                map.put("userName", cursor.getString(1));
            }
} 

將 DBController 類構造函數更改為此
數據庫控制器類

private Context context;
public DBController(Context applicationcontext) 
{
    this.context = context;
    super(applicationcontext, "user.db", null, 1);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM