从数据库获取数据的NullPointerException

时间:2013-01-15 00:28:20

标签: android multithreading nullpointerexception

我之前已经在同步数据库上制作了源代码,但突然间它现在无法正常工作。在这里,我正在尝试在DB_User类的本地数据库中读取我的记录。但它返回了java.lang.NullPointerException。所以这就是我所做的。

这是我的错误的堆栈跟踪

01-15 06:42:20.080: I/ActivityManager(60): Displayed activity com.yolanda.ta/.DBSynchronizer: 387 ms (total 387 ms)
01-15 06:42:40.639: D/dalvikvm(1147): GC_FOR_MALLOC freed 2008 objects / 125592 bytes in 74ms
01-15 06:43:21.149: D/dalvikvm(1147): GC_FOR_MALLOC freed 777 objects / 219464 bytes     in 79ms
01-15 06:44:02.018: D/dalvikvm(1147): GC_FOR_MALLOC freed 830 objects / 404856 bytes     in 67ms
01-15 06:44:35.578: D/dalvikvm(1147): GC_FOR_MALLOC freed 830 objects / 404976 bytes in 78ms
01-15 06:44:58.399: W/dalvikvm(1147): threadid=7: thread exiting with uncaught exception (group=0x4001d800)
01-15 06:44:58.411: E/AndroidRuntime(1147): FATAL EXCEPTION: Thread-8
01-15 06:44:58.411: E/AndroidRuntime(1147): java.lang.NullPointerException
01-15 06:44:58.411: E/AndroidRuntime(1147):     at com.yolanda.ta.ThreadUser.fetchLocal(ThreadUser.java:192)
01-15 06:44:58.411: E/AndroidRuntime(1147):     at com.yolanda.ta.ThreadUser.run(ThreadUser.java:59)
01-15 06:44:58.492: W/ActivityManager(60):   Force finishing activity com.yolanda.ta/.DBSynchronizer

这是fetchLocal()从数据库中获取数据,我将其称为从本地数据库获取数据

public String[] fetchLocal (int column)
{
Cursor user = mDbHelper.getAllRow3();
    String Result[] = new String[user.getCount()];
    user.moveToFirst();
    int i = 0;
    while (user.isAfterLast() == false) {
        Result[i++] = user.getString(column);
        user.moveToNext();
    }
    user.close();
    return Result;
}

这是getAllRow3()

的方法
public Cursor getAllRow3()
{
Cursor c = db.query(NAMA_TABEL, new String[]{ROW_ID, ROW_NAMAL, ROW_NAMA, ROW_PW, ROW_ALAMAT, ROW_TELEPON, ROW_LEVEL, ROW_STATUS,ROW_TIME}, null, null, null, null, null, null);
return c;
}

这是我的表结构

public class DB_User {
private static final String ROW_ID = "IDUser";
private static final String ROW_NAMAL = "NamaLogin";
private static final String ROW_NAMA ="NamaUser";
private static final String ROW_PW ="PasswordUser";
private static final String ROW_ALAMAT ="AlamatUser";
private static final String ROW_TELEPON ="TeleponUser";
private static final String ROW_LEVEL ="LevelUser";
private static final String ROW_STATUS ="StatusUser";
private static final String ROW_TIME ="Waktu";

private static final String NAMA_DB = "TA";
private static final String NAMA_TABEL = "User";
private static final int DB_VERSION = 1;
private static int batas = 5;
private static final String CREATE_TABLE = "create table if not exists "+ NAMA_TABEL +" ("+ ROW_ID +" INTEGER PRIMARY KEY AUTOINCREMENT," +
        ROW_NAMAL +" VARCHAR not null, "+ ROW_NAMA +" VARCHAR not null, " + ROW_PW + " VARCHAR not null, " + ROW_ALAMAT + " VARCHAR not null, " 
        + ROW_TELEPON + " VARCHAR, "+ ROW_LEVEL+ " VARCHAR not null, "  + ROW_STATUS + " INTEGER not null, "+ROW_TIME+"  LONG not null)";

我没有任何想法,因为其他活动可以使用相同的查询获得完全相同的数据,而我的线程不能。欢迎提出任何建议。

编辑: 第192行:Cursor user = mDbHelper.getAllRow3(); 第59行:String[] LocalRowID = fetchLocal(0);

这是我的ThreadUser代码:

public class ThreadUser  extends Thread implements Runnable {

private boolean RunSync = false;     
private DB_User mDbHelper;
private long sleeptime;

public void setDatabase(DB_User mDbHelper)
{
    this.mDbHelper = mDbHelper;
}

public void setRun(boolean set)
{
    RunSync = set;
}

public void setDelay(long delay)
{
    sleeptime = delay;
}

@Override
public void run()
{
    while(RunSync)
    {
    String[] RemoteID = fetch("http://10.0.2.2/project/User.php?ct=Sel_IDUser");
    String[] RemoteNamaL = fetch("http://10.0.2.2/project/User.php?ct=Sel_NamaLogin");
    String[] RemoteNama = fetch("http://10.0.2.2/project/User.php?ct=Sel_NamaUser");
    String[] RemotePassword = fetch("http://10.0.2.2/project/User.php?ct=Sel_PasswordUser");
    String[] RemoteAlamat = fetch("http://10.0.2.2/project/User.php?ct=Sel_AlamatUser");
    String[] RemoteTelepon = fetch("http://10.0.2.2/project/User.php?ct=Sel_TeleponUser");
    String[] RemoteLevel = fetch("http://10.0.2.2/project/User.php?ct=Sel_LevelUser");
    String[] RemoteStatus = fetch("http://10.0.2.2/project/User.php?ct=Sel_StatusUser");
    String[] RemoteTime = fetch("http://10.0.2.2/project/User.php?ct=Sel_Waktu");
    //ROW_ID, ROW_NAMAL, ROW_NAMA, ROW_PW, ROW_ALAMAT, ROW_TELEPON, ROW_LEVEL, ROW_STATUS,ROW_TIME
    String[] LocalRowID = fetchLocal(0);
    String[] LocalNamaL = fetchLocal(1);
    String[] LocalNama = fetchLocal(2);
    String[] LocalPassword = fetchLocal(3);
    String[] LocalAlamat = fetchLocal(4);
    String[] LocalTelepon = fetchLocal(5);
    String[] LocalLevel = fetchLocal(6);
    String[] LocalStatus = fetchLocal(7);
    String[] LocalTime = fetchLocal(8);

    Calendar cal = Calendar.getInstance();;


    for(int i = 1; i <  RemoteID.length; i++)
    { Log.e("index remote1", Integer.toString(i));
        for(int j = 0; j < LocalRowID.length; j++)
        {
            Log.e("indexlocal1", Integer.toString(j));
            if(RemoteID[i].equalsIgnoreCase(LocalRowID[j]))
            {                   
                if(Long.parseLong(RemoteTime[i]) > Long.parseLong(LocalTime[j]))
                {
                    // //id, namal, nama, alamat, password, telepon, level, status, time
                    mDbHelper.updateBaris2(Integer.parseInt(LocalRowID[j]), RemoteNamaL[i],
                            RemoteNama[i], RemoteAlamat[i],RemotePassword[i], 
                            RemoteTelepon[i], RemoteLevel[i], Integer.parseInt(RemoteStatus[i]), cal.getTimeInMillis());
                    break;
                }
                else if (Long.parseLong(RemoteTime[i]) < Long.parseLong(LocalTime[j]))
                {
                    call("http://10.0.2.2/project/User.php?ct=EDT&namal="+LongData(LocalNamaL[j].toString())+
                            "&nama="+LongData(LocalNama[j].toString())+"&pw="+LongData(LocalPassword[j].toString())+"&alamat="+LongData(LocalAlamat[j].toString())+
                            "&telepon="+LongData(LocalTelepon[j].toString())+"&level="+LongData(LocalLevel[j].toString())+"&status="+LocalStatus[j]+"&time="
                            +cal.getTimeInMillis()+"&id="+LocalRowID[j].toString());

                    break;
                }
            }   
        }
        if (LocalRowID.length + 1 > RemoteID.length)
        {//namal, nama, alamat, password, telepon, level, status, time
            try{
            call("http://10.0.2.2/project/User.php?ct=INS&namal="+LongData(LocalNamaL[LocalRowID.length-1].toString())+
                    "&nama="+LongData(LocalNama[LocalRowID.length-1].toString())+"&pw="+LongData(LocalPassword[LocalRowID.length-1].toString())+"&alamat="+LongData(LocalAlamat[LocalRowID.length-1].toString())+
                    "&telepon="+LongData(LocalTelepon[LocalRowID.length-1].toString())+"&level="+LongData(LocalLevel[LocalRowID.length-1].toString())+"&status="+LocalStatus[LocalRowID.length-1]+"&time="
                    +cal.getTimeInMillis());    
            Log.e("nambah server","voila");
            break;
            }
            catch (Exception e){Log.e("walah",e.toString());}
        }
        else
        if (LocalRowID.length == RemoteID.length)
        {
            break;
        }
    }


    for(int i = 0; i < LocalRowID.length-1; i++)
    { Log.e("index local2", Integer.toString(i));
        if(RemoteID.length <= 1)
        {
            try{
            call("http://10.0.2.2/project/User.php?ct=INS&namal="+LongData(LocalNamaL[i].toString())+
                    "&nama="+LongData(LocalNama[i].toString())+"&pw="+LongData(LocalPassword[i].toString())+"&alamat="+LongData(LocalAlamat[i].toString())+
                    "&telepon="+LongData(LocalTelepon[i].toString())+"&level="+LongData(LocalLevel[i].toString())+"&status="+LocalStatus[i]+"&time="
                    +cal.getTimeInMillis()+"&id="+LocalRowID[i].toString());
            }
            catch(Exception e){
            Log.e("wooooy", e.toString());
            }
            }

        for(int j = 1; j < RemoteID.length; j++)
        {
            Log.e("indexremote2", Integer.toString(j));
            if(LocalRowID[i].equalsIgnoreCase(RemoteID[j]))
            {
                break;
            } 
            if (LocalRowID.length ==  RemoteID.length)
            {
                break;
            }

        }

        if (RemoteID.length-1 > LocalRowID.length)
        {
            i-=1;
        try{
                mDbHelper.addRow2(RemoteNamaL[RemoteID.length-1], RemoteNama[RemoteID.length-1], RemoteAlamat[RemoteID.length-1], RemotePassword[RemoteID.length-1],
                        RemoteTelepon[RemoteID.length-1],   RemoteLevel[RemoteID.length-1], Integer.parseInt(RemoteStatus[RemoteID.length-1]), cal.getTimeInMillis());
                break;
            }
            catch(Exception e){
                Log.e("wuuuy", e.toString());
                }
        }
        if (LocalRowID.length ==  RemoteID.length)
        {
            break;
        }


    }

    try {
        sleep(sleeptime);
    } catch (InterruptedException e) {
        break;
    }
    }
}

public String LongData (String Data)
{
    String LongData ="";

    for (int i = 0; i < Data.length(); i++) 
    {
        if (Data.charAt(i)==' ') 
        {
            LongData += '~';
        }
        else            
            LongData += Data.charAt(i);
    }
    return LongData;
}

public String[] fetchLocal (int column)
{
    Cursor user = mDbHelper.getAllRow3();       
    String Result[] = new String[user.getCount()];
    user.moveToFirst();
    int i = 0;
    while (user.isAfterLast() == false) {
        Result[i++] = user.getString(column);
        user.moveToNext();
    }
    user.close();

    return Result;
}

public String[] fetch(String url)
{        
    HttpClient httpclient = new DefaultHttpClient();
    HttpRequestBase httpRequest = null;
    HttpResponse httpResponse = null;
    InputStream inputStream = null;
    String response = "";
    StringBuffer buffer = new StringBuffer();
    httpRequest = new HttpGet(url);

    try
    {
        httpResponse = httpclient.execute(httpRequest);
    }
    catch (ClientProtocolException el)
    {
        el.printStackTrace();
    }
    catch (IOException el)
    {
        el.printStackTrace();
    }

    try
    {
        inputStream = httpResponse.getEntity().getContent();
    }
    catch (IllegalStateException el)
    {
        el.printStackTrace();
    }
    catch (IOException el)
    {
        el.printStackTrace();
    }

    byte[] data = new byte[512];
    int len = 0;

    try
    {
        while(-1 != (len = inputStream.read(data)))
        {
            buffer.append(new String(data,0,len));
        }
    }
    catch (IOException el)
    {
        el.printStackTrace();
    }

    try
    {
        inputStream.close();
    }
    catch (IOException el)
    {
        el.printStackTrace();
    }

    response = buffer.toString();
    StringParser parser = new StringParser();
    ArrayList<Object> output = parser.Parse(response);
    Object[] Output = output.toArray();
    String[] content = new String[Output.length];

    for (int i = 0; i < content.length; i++)
    {
        content[i] = Output[i].toString();
    }

    return content;
}

public String call(String url)
{
    int BUFFER_SIZE = 2000;
    InputStream in = null;

    try
    {
        in = OpenHttpConnection(url);
    }
    catch (IOException el) {
        el.printStackTrace();
        return "Error: " + el.getMessage();
    }

    InputStreamReader isr = new InputStreamReader(in);
    int charRead;

    String str = "";
    char[] inputBuffer = new char[BUFFER_SIZE];

    try
    {
        while((charRead = isr.read(inputBuffer)) > 0)
        {
            String readString = String.copyValueOf(inputBuffer, 0, charRead);
            str += readString;
            inputBuffer = new char[BUFFER_SIZE];
        }
        in.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
        return "Error 02";
    }
    return str;
}

private InputStream OpenHttpConnection(String urlString) throws IOException
{
    InputStream in = null;
    int response = -1;

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();

    if(!(conn instanceof HttpURLConnection)) throw new IOException("Not an Http Connection");

    try
    {
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();

        response = httpConn.getResponseCode();
        if(response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();
        }
    }
    catch (Exception e)
    {
        throw new IOException("Error Connecting");
    }
    return in;
}

}`

1 个答案:

答案 0 :(得分:0)

首先,您的代码没有代码行号,因此我们不知道哪一行是“ThreadUser.java:192”和“ThreadUser.java:59”。

实际上这个问题可能是同步问题,请提供有关TheadUser.java代码的更多代码详细信息。如果是这样,请添加synchronized to method或synchronized block来解决此问题。