数据在listview中不可见

时间:2014-03-12 10:58:25

标签: java android

我尝试了所有可能的情况,但是数据没有显示在数据库的列表中。我的启动活动有列表视图,在启动时是空的,当用户填写数据并从另一个活动保存时,按下后退按钮数据应显示在第一个具有列表视图的活动中,但每次数据都不显示时

MainActivty.java

package com.example.smscampaign;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;



public class Campaign_Details extends Activity  {

    private Demo selectedAdapter;
    private ArrayList<String> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_demostration);
        TextView text1=(TextView) findViewById(R.id.text1);
        TextView text2=(TextView) findViewById(R.id.text1);
        DataBaseHandler info= new DataBaseHandler(this);
        info.open();
        String data=info.getData();
        info.close();
        String[] values= new String[]{ data };  
        //txt.setText(data);
       // Button next=(Button) findViewById(R.id.next);
      //  Map<String, String[]> storage = new HashMap<String, String[]>();
     //   String[] tableItems = storage.get("ContactTable");


       // next.setOnClickListener(this);
    // final ListView listview = (ListView) findViewById(R.id.listview);


         ListView listview1 = (ListView) findViewById(R.id.listview1);
        // TextView emptyText = (TextView)findViewById(android.R.id.empty);


        //listview.setEmptyView(findViewById(R.id.empty));
    // TextView emptyText = (TextView)findViewById(android.R.id.empty);
        // listview .setEmptyView(emptyText);

        final ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < values.length; ++i) {

            list.add(values[i]);
        }
        selectedAdapter = new Demo(this,values);
         ListView listview = (ListView) findViewById(R.id.listview);
        listview.setAdapter(selectedAdapter);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

          @Override
          public void onItemClick(AdapterView<?> parent, final View view,
              int position, long id) {
              Intent n = new Intent(getApplicationContext(), SmsSend.class);
            startActivity(n);

          }
        });
    }







    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // TODO Auto-generated method stub
        getMenuInflater().inflate(R.menu.main2, menu);
        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub

        switch (item.getItemId()) {
        case R.id.nextPage:
            Intent i = new Intent(this,SmsSend.class);
            startActivity(i);
            break;

        }
        return super.onOptionsItemSelected(item);
    }
    } 

demo.java

package com.example.smscampaign;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class Demo extends ArrayAdapter{
    private Campaign_Details list1;
        // used to keep selected position in ListView
       private int selectedPos = -1;   // init value for not-selected
        private Context context;
        private String[] values;

        public Demo(Context context, String[] values) {
            super(context, R.layout.list);
            this.context = context;
            this.values = values;
        }




        public void setSelectedPosition(int pos){
        selectedPos = pos;
             // inform the view of this change
             notifyDataSetChanged();
        }
        public int getSelectedPosition(){
             return selectedPos;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                 View v = convertView;
                        LayoutInflater vi =   (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        v = vi.inflate(R.layout.list, null);

                 // get text view
                     TextView label = (TextView)v.findViewById(R.id.data);

                    if (convertView == null) {            
                        v = vi.inflate(R.layout.list, parent, false);
                    }
                    else
                        v = convertView;
                    TextView text1 = (TextView) v.findViewById(R.id.data);
                 text1.setText(values[position]); 
                    return v;
                }
        } 

activity_list_demonstration.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TableLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:stretchColumns="3" >

        <TableRow
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/textcolour"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="left"
                android:background="@drawable/green_circle" />

            <TextView
                android:id="@+id/text1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:paddingLeft="10dp"
                android:text="Active Campaign"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textColor="#4AE56B" />

            <TextView
                android:id="@+id/textnum1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginRight="130dp"
                android:background="@drawable/green_badge"
                android:gravity="center"
                android:text=" 0 "
                android:textColor="@color/white" />
        </TableRow>
    </TableLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="240dp"
        android:orientation="vertical" >

        <ListView
            android:id="@+id/listview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <TableLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:stretchColumns="3" >

        <TableRow
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/textcolour"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="left"
                android:background="@drawable/grey_circle" />

            <TextView
                android:id="@+id/text2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingLeft="10dp"
                android:text="Closed Campaign"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <TextView
                android:id="@+id/textnum2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginRight="130dp"
                android:background="@drawable/grey_badge"
                android:gravity="center"
                android:text=" 0 "
                android:textColor="@color/white" />
        </TableRow>
    </TableLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="140dp"
        android:orientation="vertical" >

        <ListView
            android:id="@+id/listview1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

</LinearLayout>

list.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" >


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

</LinearLayout>

DatabaseHandler.java//databaseclass

package com.example.smscampaign;

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



public class DataBaseHandler{

    public static final String KEY_ROWID="_id";
    public static final String KEY_NAME="person_name";
    public static final String KEY_SCALE="scale_person";

    private static final String DATABASE_NAME="Scaledb";
    private static final String DATABASE_TABLE="peopleTable";
    private static final int DATABASE_VERSION=1;

    private DbHelper ourHepler;
    private final Context ourContext;
    private SQLiteDatabase ourDatabase;
    public class DbHelper extends SQLiteOpenHelper{

        public DbHelper(Context context) {
            super(context,DATABASE_NAME,null,DATABASE_VERSION);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            db.execSQL( "CREATE TABLE " + DATABASE_TABLE + " (" +
                    KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT,  " +
                    KEY_NAME + " TEXT NOT NULL, " +
                    KEY_SCALE + " TEXT NOT NULL );"
                    );
            }

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

    }

    public DataBaseHandler(Context c){
        ourContext=c;
    }


    public DataBaseHandler open() throws SQLException{
        ourHepler = new DbHelper(ourContext);
        ourDatabase=  ourHepler.getWritableDatabase();
        return this;
    }
    public void close()
    {
        ourHepler.close();
    }


    public long entryCreate(String name, String scale) {
        // TODO Auto-generated method stub

        ContentValues cv=new ContentValues();
        cv.put(KEY_NAME, name);
        cv.put(KEY_SCALE, scale);
        return ourDatabase.insert(DATABASE_TABLE, null, cv); 

    }


    public String getData() {
        // TODO Auto-generated method stub
        String[] col= new String[]{KEY_ROWID,KEY_NAME,KEY_SCALE};
        Cursor c=  ourDatabase.query(DATABASE_TABLE, col, null, null, null, null, null);
        String run="";
        int iRow=c.getColumnIndex(KEY_ROWID);
        int iName=c.getColumnIndex(KEY_NAME);
        int iScale=c.getColumnIndex(KEY_SCALE);

        for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
            run=run+c.getString(iRow)+ " " + c.getString(iName) + " " + c.getString(iScale) + "\n";
        }

        return run;
    }


    public String getScale(long l) {
        // TODO Auto-generated method stub
        String[] col= new String[]{KEY_ROWID,KEY_NAME,KEY_SCALE};
        Cursor c= ourDatabase.query(DATABASE_TABLE, col,KEY_ROWID + "-" + l, null, null, null, null);

        if(c != null){
            c.moveToFirst();
            String scale=c.getString(2);
            return scale;
        }
        return null;
    }


    public String getName(long l)  {
        // TODO Auto-generated method stub
        String[] col= new String[]{KEY_ROWID,KEY_NAME,KEY_SCALE};
        Cursor c= ourDatabase.query(DATABASE_TABLE, col,KEY_ROWID + "-" + l, null, null, null, null);

        if(c != null){
            c.moveToFirst();
            String name=c.getString(1);
            return name;

        }
        return null;
    }


    public  void updateEntry(long lt, String mName, String mScale) {
        // TODO Auto-generated method stub
          ContentValues cvUpdate=new ContentValues();   
          cvUpdate.put(KEY_NAME,mName);
          cvUpdate.put(KEY_SCALE,mScale);
          ourDatabase.update(DATABASE_TABLE,  cvUpdate, KEY_ROWID + "-" + lt, null);
    }


    public void deleteEntry(long ltt) throws SQLException{
        // TODO Auto-generated method stub
        ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + ltt,null);

    }
}

4 个答案:

答案 0 :(得分:0)

更改getview方法内容。

 public static class ViewHolder{

                 public TextView text;

             }

             public View getView(int position, View convertView, ViewGroup parent) {

                 View vi = convertView;
                 ViewHolder holder;

                 if(convertView==null){

                     vi = inflater.inflate(R.layout.list, null);

                     holder = new ViewHolder();
                     holder.text = (TextView) vi.findViewById(R.id.data);

                     vi.setTag( holder );
                 }
                 else 
                     holder=(ViewHolder)vi.getTag();

此外,如果您不是自定义布局[仅使用textview],请通过选择默认布局直接使用arrayadapter。

答案 1 :(得分:0)

  

按下后退按钮,数据应显示在第一个活动

您使用onCreate()方法编写数据库加载代码,该方法在其生命周期中执行一次,即当您的应用程序启动时或活动在方向更改时被销毁时。

因此,当您按下后退按钮时,onCreate()尚未调用,同样将继续显示列表。

一些建议:

  

如果您在onResume()

中编写所有数据库内容,那就太好了      

否则在主要活动的onPause()方法中调用finish(),然后再次通过您对second_activity的后退方法的意图启动它。finish()会在您转到下一个活动时终止该活动。当你从第二个到第二个strtaActivity,然后是相应的意图时再次重新创建。

如果从数据库获取数据并将其放入String数组中,则使用StringTokenizer也会更好。

答案 2 :(得分:0)

您需要在某些地方进行更改。您已将您的arraylist全局声明为

private ArrayList<String> list;

之后再次在onCreate()方法

上声明
final ArrayList<String> list = new ArrayList<String>();

所以用

替换它
list = new ArrayList<String>();

现在,您的所有数据都会添加到列表中,但在您的适配器中,您已经传递了字符串数组。所以你还需要改变

 selectedAdapter = new Demo(this,values);

 selectedAdapter = new Demo(this,list);

答案 3 :(得分:0)

在你写的ArrayAdapter

if (convertView == null) {
    v = vi.inflate(R.layout.list, parent, false);
} else
    v = convertView;

删除else语句。或者更确切地说,删除完整的if-else语句。也 TextView text1 = (TextView) v.findViewById(R.id.data);是您已在TextView

中定义此特定label的额外内容

修改

public Demo(Context context, String[] values) {
        super(context, R.layout.list);
        this.context = context;
        this.values = values;
    }

public Demo(Context context, String[] values) {
        super(context, R.layout.list,values);
        this.context = context;
        this.values = values;
    }