jeudi 7 avril 2016

Custom List View with Cursor Adapter not working

I want to create a custom listview with SQLite database. Later I will add buttons on the listitem as well. It seems to be simple. But I'm trying it for a long time and it's not working. Can anyone please help me out where I am making the mistake?

Here are my Code

MyActivity.java

import android.app.Activity;
import android.app.ListActivity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ListActivity {

    MyCursorAdapter customAdapter;
    private Cursor mCursor;
    private ListView listView;

    // Default constructor
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);

       // listView = (ListView) findViewById(R.id.activity_main);

        DBHelper dbh= new DBHelper(this);
        mCursor= (Cursor) dbh.getAllCotacts();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> a, View v, int position, long id) {
            }
        });


        new Handler().post(new Runnable() {

            //@Override
            public void run() {
                customAdapter = new MyCursorAdapter(MainActivity.this, mCursor, 0);

                listView.setAdapter(customAdapter);
            }

        });
    }

}    

DBHelper.java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;

public class DBHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "MyDBName.db";
    public static final String MY_TABLE_NAME = "MyTable";
    public static final String COLUMN_TITLE = "title";
    public static final String COLUMN_BODY= "body";
    public static final String COLUMN_ID="id";

    private HashMap hp;

    public DBHelper(Context context)
    {
        super(context, DATABASE_NAME , null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(
                "create table contacts " +
                        "(title text, body text)"
        );
        db.execSQL("INSERT INTO TABLE MyTable"+"(title, body)"+"VALUES(My Favourite title1, My Favourite Post1)");
        db.execSQL("INSERT INTO TABLE MyTable"+"(title, body)"+"VALUES(My Favourite title2, My Favourite Post2)");
        db.execSQL("INSERT INTO TABLE MyTable"+"(title, body)"+"VALUES(My Favourite title3, My Favourite Post3)");
        db.execSQL("INSERT INTO TABLE MyTable"+"(title, body)"+"VALUES(My Favourite title4, My Favourite Post4)");
        db.execSQL("getAllCotacts()");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS contacts");
        onCreate(db);
    }

    public boolean insertContact  (String title, String body, String id)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("title", title);
        contentValues.put("body", body);
        contentValues.put("id", id);

        db.insert("contacts", null, contentValues);
        return true;
    }

    public Cursor getData(int id){
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from contacts where id="+id+"", null );
        return res;
    }

    public int numberOfRows(){
        SQLiteDatabase db = this.getReadableDatabase();
        int numRows = (int) DatabaseUtils.queryNumEntries(db, MY_TABLE_NAME);
        return numRows;
    }

    public boolean updateContact (String id, String title, String body)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("id", id);
        contentValues.put("title", title);
        contentValues.put("body", body);

        db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(Integer.parseInt(id)) } );
        return true;
    }

    public Integer deleteContact (Integer id)
    {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete("contacts",
                "id = ? ",
                new String[] { Integer.toString(id) });
    }

    public ArrayList<String> getAllCotacts()
    {
        ArrayList<String> array_list = new ArrayList<String>();

        //hp = new HashMap();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from MyTable", null );
        res.moveToFirst();

        while(res.isAfterLast() == false){
            array_list.add(res.getString(res.getColumnIndex(COLUMN_TITLE)));
            res.moveToNext();
        }
        return array_list;
    }
}

MyCursorAdapter.java

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CursorAdapter;
import android.widget.TextView;
import java.util.List;

public class MyCursorAdapter extends CursorAdapter {
    private Context context;
    DBHelper dbh= new DBHelper(context);
    private LayoutInflater cursorInflater;

    // Default constructor
    public MyCursorAdapter(Context context, Cursor cursor, int flags) {
        super(context, cursor, flags);
        cursorInflater = (LayoutInflater) context.getSystemService(
                Context.LAYOUT_INFLATER_SERVICE);

    }

    public void bindView(View view, Context context, Cursor cursor) {

      /*  if(cursor.getPosition()%2==1) {
            view.setBackgroundColor(context.getResources().getColor(R.color.background_odd));
        }
        else {
            view.setBackgroundColor(context.getResources().getColor(R.color.background_even));
        }*/
        TextView textViewTitle = (TextView) view.findViewById(R.id.articleTitle);
        String title = cursor.getString( cursor.getColumnIndex( DBHelper.COLUMN_TITLE ) );
        textViewTitle.setText(title);

        TextView textViewBody= (TextView) view.findViewById(R.id.articleBody);
        String body= cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_BODY));
        textViewBody.setText(body);

    }

    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        // R.layout.list_row is your xml layout for each row
        return cursorInflater.inflate(R.layout.item_todo, parent, false);
    }
}

item_todo.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://ift.tt/nIICcg"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    <TextView
        android:id="@+id/articleTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Study cursors"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <TextView
        android:id="@+id/articleBody"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:text="BODY"
        android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>

activity_main.xml

<LinearLayout xmlns:android="http://ift.tt/nIICcg"
    xmlns:tools="http://ift.tt/LrGmb4" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    >


    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listView"></ListView>

</LinearLayout>

I am taking help from online tutorials. It's not working. Please hep me out.

here is the error:

FAILURE: Build failed with an exception.

  • What went wrong:
    A problem occurred configuring root project 'CustomListViewEx2'.

    Could not resolve all dependencies for configuration ':classpath'. Could not resolve com.intellij:annotations:12.0. Required by:
    :CustomListViewEx2:unspecified > com.android.tools.build:gradle:2.1.0-alpha3 > com.android.tools.build:gradle-core:2.1.0-alpha3 > com.android.tools.build:builder:2.1 .0-alpha3 > com.android.tools:sdklib:25.1.0-alpha3 > com.android.tools.layoutlib:layout lib-api:25.1.0-alpha3 Could not resolve com.intellij:annotations:12.0. Could not get resource 'http://ift.tt/1MgPNL8 /12.0/annotations-12.0.pom'. Failed to move file 'C:\Users\SouRAV\AppData\Local\Temp\gradle_download83 65426972313668671bin' into filestore at 'C:\Users\SouRAV.gradle\caches\modules-2\files -2.1\com.intellij\annotations\12.0\aaa1796465aa46f478176c06456397418b34d2b3\annotations -12.0.pom'

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 19 mins 34.177 secs

Aucun commentaire:

Enregistrer un commentaire