2011-11-06 57 views
0

所以我遇到了一个奇怪的问题。我正在尝试将数据文件写入设备。我在2.2版的eclipse中开发了应用程序,我的设备是2.3.3,所以我让仿真器运行在2.3.3上,它将文件写入正确。为什么这不适用于设备?它也被编码以将设备上的数据库文件复制到php服务器。在服务器上的文件基本上是空的,我也从设备中拉出数据库文件,它是空的。它唯一的工作时间是在模拟器上,我在服务器上得到一个合法的文件,当我拉数据库时,它有数据。我很迷茫。如果你想看到一些代码,然后问,我会张贴一些,但有40多个班,我真的不知道从哪里开始。 在此先感谢。可以写入文件到服务器在模拟器但不是设备?

下面是有关数据库创建

import android.content.Context; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper; 
import android.util.Log; 

public class DbHelper extends SQLiteOpenHelper { 

private static final String DATABASE_NAME = "database"; 
private static final int DATABASE_VERSION = 1; 

// Database creation sql statement 
private static final String DATABASE_CREATE = "create table database (_id integer  primary key autoincrement," + 
    "name text not null);"; 

public DbHelper(Context context) { 
    super(context, DATABASE_NAME, null, DATABASE_VERSION); 
} 

// Method is called during creation of the database 
@Override 
public void onCreate(SQLiteDatabase database) { 
    database.execSQL(DATABASE_CREATE); 
} 

// Method is called during an upgrade of the database, e.g. if you increase 
// the database version 
@Override 
public void onUpgrade(SQLiteDatabase database, int oldVersion, 
     int newVersion) { 
    Log.w(DbHelper.class.getName(), 
      "Upgrading database from version " + oldVersion + " to " 
        + newVersion + ", which will destroy all old data"); 
    database.execSQL("DROP TABLE IF EXISTS database"); 
    onCreate(database); 
} 
} 

这里是适配器代码..

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

public class DbAdapter { 

// Database fields 
public static final String KEY_ROWID = "_id"; 
public static final String KEY_NAME = "name"; 

static final String DATABASE_TABLE = "database"; 
private Context context; 
private SQLiteDatabase database; 
private DbHelper dbHelper; 


public DbAdapter(Context ctx) { 
    context = ctx; 

} 

public SQLiteDatabase openToRead() throws SQLException { 
    dbHelper = new DbHelper(context); 
    database = dbHelper.getReadableDatabase(); 

    return database; 
} 

public SQLiteDatabase open() throws SQLException { 
    dbHelper = new DbHelper(context); 
    database = dbHelper.getWritableDatabase(); 

    return database; 
} 

public void close() { 
    dbHelper.close(); 
} 

// 
/** 
* Create a new todo If the todo is successfully created return the new 
* rowId for that note, otherwise return a -1 to indicate failure. 
*/ 

public long createRow(String name) { 
    ContentValues initialValues = createContentValues(name); 

    return database.insert(DATABASE_TABLE, null, initialValues); 
} 


/** 
* Update the todo 
*/ 

public boolean updateRows(long rowId, 
     String name) { 

    ContentValues updateValues = createContentValues(
      name); 

    return database.update(DATABASE_TABLE, updateValues, KEY_ROWID + "=" 
      + rowId, null) > 0; 
} 


/** 
* Deletes todo 
*/ 

public boolean deleteRow(long rowId) { 
    return database.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0; 
} 


/** 
* Return a Cursor over the list of all todo in the database 
* 
* @return Cursor over all notes 
*/ 

public Cursor fetchAllRows() { 
    return database.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME}, null, null, null, 
      null, null); 
} 


/** 
* Return a Cursor positioned at the defined todo 
*/ 

public Cursor fetchRow(long rowId) throws SQLException { 
    Cursor mCursor = database.query(true, DATABASE_TABLE, new String[] { 
      KEY_ROWID ,KEY_NAME}, 
      KEY_ROWID + "=" + rowId, null, null, null, null, null); 
    if (mCursor != null) { 
     mCursor.moveToFirst(); 
    } 
    return mCursor; 
} 

/**fetches keyword**/ 
public Cursor fetchKeyword(String keyword, String column, String[] columns) throws SQLException { 


    Cursor mCursor = database.query(DATABASE_TABLE, columns, column + "='" + keyword + "'", 
      null, null, null, null); 
    if (mCursor != null) { 
     mCursor.moveToFirst(); 
    } 
    return mCursor; 
} 

private ContentValues createContentValues(String name){ 

    ContentValues values = new ContentValues(); 
    values.put(KEY_NAME, name); 
    return values; 
} 

//returns (an) entire column(s), all rows 
public Cursor fetchColumns(String[] colnames) { 
    Cursor mCursor = database.query(DATABASE_TABLE, colnames, null, 
      null, null, null, null); 
    if (mCursor != null) { 
     mCursor.moveToFirst(); 
    } 
    return mCursor; 
} 

}

好吧,我孤立它这三个类..下面是创建条目并将其上传到服务器的类。据我可以告诉数据库不被创建正确的方式..在有文件

public class CreateName extends Activity{ 

//variables 
private DbAdapter mDbHelper; 
EditText textField; 
TextView txtEnter2; 
TextView txtEnter; 
Button btnSubmit; 
Context context; 
SharedPreferences prefs; 
SharedPreferences.Editor spe; 
SQLiteDatabase db; 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.submit); 

    //constructors 
    context = getApplicationContext(); 
    prefs = PreferenceManager.getDefaultSharedPreferences(context); 
    spe = prefs.edit(); 


    init(); 
    listen(); 
} 

public void checker() { 
    Intent i = new Intent(this, MoveForward.class); 
    startActivity(i); 
} 

private void listen() { 
    btnSubmit.setOnClickListener(new Button.OnClickListener() 
    { 
     public void onClick (View v) 
     { 
      mDbHelper = new DbAdapter(context); 
      String words = textField.getText().toString(); 
      Log.v(words, words); 
      mDbHelper.open(); 
      mDbHelper.createRow(words); 
      mDbHelper.close(); 
      spe.putString("name", words); 
      spe.commit(); 

      PHPBuddy buddy = new PHPBuddy(); 
      try { 
       buddy.uploadFile("database"); 
      } catch (Exception e) { 
       // ask the user to retry 
       e.printStackTrace(); 
      } 
      checker(); 

     } 
    } 
    );  
} 

private void init() { 

    textField = (EditText)findViewById(R.id.edtTxt); 
    txtEnter2 = (TextView)findViewById(R.id.txtEnter2); 
    txtEnter = (TextView)findViewById(R.id.txtEnter); 
    btnSubmit =(Button)findViewById(R.id.btnSubmit); 
    txtEnter.setText("Enter your proper name"); 
    txtEnter2.setText("ex: John Smith"); 




} 

}

也许有一个光标或DB我差点忘中没有表关闭?

这里是更多的代码..

public class SBMain extends Activity { 

Button btnSpinner; 
String[] items; 
String text; 
Spinner s; 
Intent i, j; 
int activity; 
SharedPreferences prefs; 
SharedPreferences.Editor spe; 
SQLiteDatabase db; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.spinnerscreen); 

    prefs = PreferenceManager.getDefaultSharedPreferences(this); 
    spe = prefs.edit(); 
    init(); 
    fillSpinner(); 

    btnSpinner.setOnClickListener(new Button.OnClickListener() 
    { 
     public void onClick (View v) 
     { 

      Cursor cc = (Cursor)(s.getSelectedItem()); 
      if (cc != null) { 
       text = cc.getString(cc.getColumnIndex("name")); 
      } 
      checker(); 
     } 
    }); 

} 

public void checker() { 

    if (text .equals("Create Name")){ 
     i = new Intent(this, GetName.class); 
     spe.putString("name", text); 
     spe.commit(); 
     startActivity(i); 

    }else{ 
     spe.putString("name", text); 
     spe.commit(); 
     i = new Intent(this, MoveForward.class); 
     startActivity(i); 

    } 

} 

private void fillSpinner(){ 
    DbAdapter mDbHelper = new DbAdapter(this); 
    mDbHelper.open(); 
    Cursor c = mDbHelper.fetchColumns(new String[] {"_id","name"});; 

    if (! c.moveToFirst()){ 
     c.close(); 

     mDbHelper.createRow("Create Name"); 
     mDbHelper.close(); 
     c = mDbHelper.fetchColumns(new String[] {"_id","name"}); 

    }else{ 
     mDbHelper.close(); 
    } 


    // create an array to specify which fields we want to display 
    String[] from = new String[]{"name"}; 
    // create an array of the display item we want to bind our data to 
    int[] to = new int[]{android.R.id.text1}; 
    // create simple cursor adapter 

    SimpleCursorAdapter adapter = 
     new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to); 


    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    // get reference to our spinner 

    s.setAdapter(adapter); 

} 

private void init() { 

    btnSpinner = (Button)findViewById(R.id.btnSpinner); 
    s = (Spinner) findViewById(R.id.spinner1); 


} 

}

这里是飞溅的活动,下载文件

public class Splash extends Activity{ 

String file_url = "http://ipaddress/xampp/uploads/"; 
Context context = this; 
/** Called when the activity is first created. */ 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.splash); 

    Thread splashThread = new Thread() { 
     @Override 
     public void run() { 
      float percent = 0; 
      try { 
       int waited = 0; 
       int time = 1000; 
       while (waited < time) { 
        sleep(100); 
        waited += 100; 
        String perc = Integer.toString(waited/time); 

       } 
      } catch (InterruptedException e) { 
       // do nothing 
      } finally { 



       //if this is the apps first time running, get a list of names. 
       if(isFirstRun()){ 
        PHPBuddy buddy = new PHPBuddy(); 
         try { 
          buddy.downloadFile("database"); 
         } catch (IOException e) { 
          // TODO Auto-generated catch block 
          e.printStackTrace(); 
         } 

        //ToDo add spared prefs editor to set isfirstrun to true 
        Intent i = new Intent(); 
        i.setClassName("com.project", 


        "com.project.SBMain"); 
        startActivity(i); 

       }else{ 
        //make registered user page 
        Intent i = new Intent(); 
        //ToDo add spared prefs editor to set isfrstrun to false 
        //ToDo add intent for true 
       } 
       finish(); 
      } 
     } 
    }; 
    splashThread.start(); 
} 

public boolean isFirstRun(){ 

    String rb = "isfirstrun"; 
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); 
    SharedPreferences.Editor spe; 
    spe = prefs.edit(); 
    //spe.putBoolean("isfirstrun", true); 
    //boolean test = prefs.getBoolean(rb, true); 
    return true;//prefs.getBoolean(rb, true); 
} 

}

这里是PHP

<?php 
$myFile = "requestslog.txt"; 
$fh = fopen($myFile, 'a') or die("can't open file"); 
fwrite($fh, "\n\n---------------------------------------------------------------\n"); 
foreach($_SERVER as $h=>$v) 
    if(ereg('HTTP_(.+)',$h,$hp)) 
     fwrite($fh, "$h = $v\n"); 
fwrite($fh, "\r\n"); 
fwrite($fh, file_get_contents('php://input')); 
fclose($fh); 
echo "<html><head /><body><iframe src=\"$myFile\" style=\"height:100%; width:100%;\"> </iframe></body></html>" 
?> 
<?php 
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) { 
echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n"; 
move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $_FILES['userfile'] ['name']); 
} else { 
echo "Possible file upload attack: "; 
echo "filename '". $_FILES['userfile']['tmp_name'] . "'."; 
print_r($_FILES); 
    } 
    ?> 
+0

你在哪里写数据文件?所有这些代码都是数据库创建/插入。 –

+0

getWritableDatabase()似乎是一个可疑的嫌疑犯,是你的还是我不熟悉的Android调用? –

+0

getWritableDatabase()是SQLiteOpenHelper()中的一个方法http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper。html – tricknology

回答

0

我想我明白了。
首先,我设置了一个类,在创建数据库后立即将数据库复制到SD卡;从那里,我检查了这个文件,看到它确实完好无损。 然后,我将复制调用移动到数据库发送到服务器之前的地方。它在“SQLite数据库浏览器”中看起来不太好,所以我在Firefox的SQLite管理器中打开它,所有的数据都在那里。所以,在Firefox中,我会查看上传到服务器的文件。在SQLite数据库浏览器中看起来很空的数据里面有数据!

0

我的第一个猜测是你正试图将数据库写入你没有权限的地方。

我会推荐使用您的Activity的方法File getDir (String name, int mode)在您的应用程序中获取可读写的文件夹。

+0

我已经在清单中设置了权限。我会尝试这种方法以及写入SD卡并回复给您。你们有什么理由可以让所有的东西在模拟器上工作,但不是电话吗?这可能是事实,这款手机曾经扎根? – tricknology

+0

请注意,当我使用这段代码时,数据库是在/data/data/project.path/databases/中创建的,它应该有权在默认情况下写入,否? – tricknology

+0

您的设备上的文件系统结构可能与模拟器上的不同 – JeanLuc

相关问题