2011-11-06 4 views
0

그래서 나는 특이한 문제를 겪었습니다. 장치에 데이터 파일을 쓰려고합니다. 나는 이클립스 2.2에서 응용 프로그램을 개발, 내 장치 2.3.3, 그래서 2.3.3에서 실행 에뮬레이터를 만들었습니다, 잘 파일을 씁니다. 왜이 장치에서 작동하지 않습니까? 또한 장치의 데이터베이스 파일을 PHP 서버로 복사하도록 코딩되어 있습니다. 서버에서 파일은 본질적으로 비어 있습니다. 나는 장치에서 db 파일을 가져 왔고 비어 있습니다. 그것은 작동하는 유일한 시간은 에뮬레이터에, 내가 서버에 합법 파일을 얻을 때 내가 그것을 끌어 데이터를 가져옵니다. 나는 너무 길다. 몇 가지 코드를보고 싶다면 몇 가지를 게시했지만 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 관리자에서 열어서 모든 데이터가 거기에있었습니다. 그래서 파이어 폭스에서는 서버에 업로드 된 파일을 살펴 봅니다. SQLite 데이터베이스 브라우저에서 비어있는 것은 데이터가 들어 있습니다!

0

내 첫 번째 추측은 권한이없는 곳에 데이터베이스를 작성하려고한다는 것입니다.

ActivityFile getDir (String name, int mode) 메소드를 사용하여 읽고 쓸 수있는 앱 내 폴더를 얻는 것이 좋습니다.

+0

매니페스트에서 권한을 설정했습니다. 나는 그 방법을 시도 할뿐만 아니라 SD 카드에 글을 쓰고 다시 연락 할 것이다. 여러분이 알고있는 이유가 있습니까? 에뮬레이터에서는 작동하지만 전화에서는 작동하지 않을 수 있습니다. 이 전화가 한때 뿌리를 냈다는 사실 일 수 있습니까? – tricknology

+0

참고로이 코드를 사용할 때 /data/data/project.path/databases/에 데이터베이스가 생성됩니다. 기본적으로 거기에 쓸 수있는 권한이 있어야합니다. – tricknology

+0

파일 시스템 구조가 에뮬레이터에서와 다른 것일 수도 있습니다. – JeanLuc

관련 문제