2012-02-29 3 views
1

я думал, что это работает, но теперь его нет, просто предположит, чтобы загрузить затем открыть скачать в.в. добавлен некоторой СОюсохранения JSON внешней памяти в настоящее время не работает

public class MainActivity extends Activity { 

String entityString = null; 
String storyObj = ""; 
Object json = null; 
HttpEntity entity = null; 
InputStream is = null; 
Integer responseInteger = null; 

//external storage check 
boolean storageAvailable = false; 
boolean storageWriteable = false; 
String state = Environment.getExternalStorageState(); 

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

    Button downloadBtn = (Button) findViewById(R.id.downloadButton); 
    downloadBtn.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 

      saveToExternal(); 

     } 
    }); 

    Button loadBtn = (Button) findViewById(R.id.loadButton); 
    loadBtn.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 

      loadExternal(); 

     } 
    }); 


//end of onCreate() 
} 


public void saveToExternal(){ 
    TextView test = (TextView) findViewById(R.id.textView); 


    try{ 
     //connects to mySQL 
     HttpClient client = new DefaultHttpClient(); 
     HttpPost post = new HttpPost("http://10.0.2.2/textures_story_list.php"); 
     HttpResponse response = client.execute(post); 
     //captures the response 
     entity = response.getEntity(); 
     InputStream entityStream = entity.getContent(); 
     StringBuilder entityStringBuilder = new StringBuilder(); 
     byte [] buffer = new byte[1024]; 
     int bytesReadCount; 
     while ((bytesReadCount = entityStream.read(buffer)) > 0) { 
      entityStringBuilder.append(new String(buffer, 0, bytesReadCount)); 
     } 
     entityString = entityStringBuilder.toString(); 
     //responseInteger = Integer.valueOf(entityString); 
    }catch(Exception e) { 
     Log.e("log_tag", "Error in http connection "+e.toString()); 
    } 

    //writes as String from entityString to external memory 

    //first check storage state 
    try{ 

     if (Environment.MEDIA_MOUNTED.equals(state)){ 
      storageAvailable = storageWriteable = true; 
     } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){ 
      storageAvailable = true; 
      storageWriteable = false; 
     } else storageAvailable = storageWriteable = false; 


     if(storageAvailable && storageWriteable) { 
      File extFile = new File(Environment.getExternalStorageDirectory(), "/android/data/com.game/story.json"); 
      FileOutputStream out = new FileOutputStream(extFile); 

      out.write(entityString.getBytes()); 
      out.flush(); 
      out.close(); 
     } 




    }catch(Exception e) { 
     Log.e("log_tag", "Error saving string "+e.toString()); 
    } 

//end of saveJson() 
} 

public void loadExternal(){ 
    TextView test = (TextView) findViewById(R.id.textView); 

    //loads the files 
    try{ 

     FileInputStream fileInput = openFileInput("/android/data/com.game/story.json"); 

     BufferedReader inputReader = new BufferedReader(new InputStreamReader(fileInput, "UTF-8"), 8); 
     StringBuilder strBuilder = new StringBuilder(); 
      String line = null; 
      while ((line = inputReader.readLine()) != null) { 
       strBuilder.append(line + "\n"); 
      } 
      fileInput.close(); 
      storyObj = strBuilder.toString(); 

    }catch(IOException e){ 
     Log.e("log_tag", "Error building string "+e.toString()); 
    } 

    try{ 
     JSONArray jArray = new JSONArray(storyObj); 
     String storyNames = ""; 
     for(int i = 0;i<jArray.length();i++){ 
      storyNames += jArray.getJSONObject(i).getString("story_name") +"\n"; 
     } 
     test.setText(storyNames); 

    }catch(JSONException e) { 
     Log.e("log_tag", "Error returning string "+e.toString()); 
    } 
    return; 
//and of openJson() 
} 




//end of class body  
} 

ошибка говорит, что это не имеет никакого файл истории. json кто-нибудь знает, какие коды им не хватает, чтобы исправить это? моя ошибка теперь

Error saving string java.io.FileNotFoundException: /mnt/sdcard/android/data/com.game/story.json (No such file or directory) 
+0

Я думаю, что вы храните файл в externalStorage (/ Android/данные/com.your.package /) и попробуйте загрузить из пакета dir (/data/data/com.your.package) –

+0

, так как я реализую это в этом коде, я все еще изучаю – daniel

+0

это моя ошибка при сохранении файла. Ошибка при сохранении файла строка java.io.FileN otFoundException: /mnt/sdcard/android/data/com.game/story.json (Нет такого файла или каталога) – daniel

ответ

1

Нечто подобное:

.......... 
String content = loadFromHttp(); 
savedToExternal(content, "story.json"); 
String res = loadFromExternal("story.json"); 
.......... 


private void savedToExternal(String content, String fileName) { 
    FileOutputStream fos = null; 
    Writer out = null; 
    try { 
     File file = new File(getAppRootDir(), fileName); 
     fos = new FileOutputStream(file); 
     out = new OutputStreamWriter(fos, "UTF-8"); 

     out.write(content); 
     out.flush(); 
    } catch (Throwable e){ 
     e.printStackTrace(); 
    } finally { 
     if(fos!=null){ 
      try { 
       fos.close(); 
      } catch (IOException ignored) {} 
     } 
     if(out!= null){ 
      try { 
       out.close(); 
      } catch (IOException ignored) {} 
     } 
    } 
} 

private String loadFromExternal(String fileName) { 
    String res = null; 
    File file = new File(getAppRootDir(), fileName); 
    if(!file.exists()){ 
     Log.e("", "file " +file.getAbsolutePath()+ " not found"); 
     return null; 
    } 
    FileInputStream fis = null; 
    BufferedReader inputReader = null; 
    try { 
     fis = new FileInputStream(file); 
     inputReader = new BufferedReader(new InputStreamReader(fis, "UTF-8")); 
     StringBuilder strBuilder = new StringBuilder(); 
     String line; 
     while ((line = inputReader.readLine()) != null) { 
      strBuilder.append(line + "\n"); 
     } 
     res = strBuilder.toString(); 
    } catch(Throwable e){ 
     if(fis!=null){ 
      try { 
       fis.close(); 
      } catch (IOException ignored) {} 
     } 
     if(inputReader!= null){ 
      try { 
       inputReader.close(); 
      } catch (IOException ignored) {} 
     } 
    } 
    return res; 
} 

public File getAppRootDir() { 
    File appRootDir; 
    boolean externalStorageAvailable; 
    boolean externalStorageWriteable; 
    String state = Environment.getExternalStorageState(); 
    if (Environment.MEDIA_MOUNTED.equals(state)) { 
     externalStorageAvailable = externalStorageWriteable = true; 
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { 
     externalStorageAvailable = true; 
     externalStorageWriteable = false; 
    } else { 
     externalStorageAvailable = externalStorageWriteable = false; 
    } 
    if (externalStorageAvailable && externalStorageWriteable) { 
     appRootDir = getExternalFilesDir(null); 
    } else { 
     appRootDir = getDir("appRootDir", MODE_PRIVATE); 
    } 
    if (!appRootDir.exists()) { 
     appRootDir.mkdir(); 
    } 
    return appRootDir; 
} 
............ 
+0

поэтому где (String content, String fileName), следуя моему коду, я заменяю содержимое entityStream и имя файла историей. ???? JSON – daniel

+0

entryString is content, story.json is fileName –

+0

kelw Спасибо, я делал это по-другому, не знал о наличии параметров там – daniel

0

Ok позволяет попробовать еще раз, полный код:

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

    Button downloadBtn = (Button) findViewById(R.id.downloadButton); 
    downloadBtn.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 

      saveToExternal(); 

     } 
    }); 

    Button loadBtn = (Button) findViewById(R.id.loadButton); 
    loadBtn.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 

      loadExternal(); 

     } 
    }); 


    //end of onCreate() 
} 



public void saveToExternal(){ 
    String content = loadFromNet(); 
    save(content, "story.json"); 
} 

public void loadExternal(){ 
    TextView test = (TextView) findViewById(R.id.textView); 
    String res = load("story.json"); 
    test.setText(res); 
} 

private String loadFromNet(){ 
    String result = null; 
    try{ 
     //connects to mySQL 
     HttpClient client = new DefaultHttpClient(); 
     HttpPost post = new HttpPost("http://10.0.2.2/textures_story_list.php"); 
     HttpResponse response = client.execute(post); 
     //captures the response 
     HttpEntity entity = response.getEntity(); 
     InputStream entityStream = entity.getContent(); 
     StringBuilder entityStringBuilder = new StringBuilder(); 
     byte [] buffer = new byte[1024]; 
     int bytesReadCount; 
     while ((bytesReadCount = entityStream.read(buffer)) > 0) { 
      entityStringBuilder.append(new String(buffer, 0, bytesReadCount)); 
     } 
     result = entityStringBuilder.toString(); 
     //responseInteger = Integer.valueOf(entityString); 
    }catch(Exception e) { 
     Log.e("log_tag", "Error in http connection "+e.toString()); 
    } 
    return result; 
} 

private void save(String content, String fileName) { 
    FileOutputStream fos = null; 
    Writer out = null; 
    try { 
     File file = new File(getAppRootDir(), fileName); 
     fos = new FileOutputStream(file); 
     out = new OutputStreamWriter(fos, "UTF-8"); 

     out.write(content); 
     out.flush(); 
    } catch (Throwable e){ 
     e.printStackTrace(); 
    } finally { 
     if(fos!=null){ 
      try { 
       fos.close(); 
      } catch (IOException ignored) {} 
     } 
     if(out!= null){ 
      try { 
       out.close(); 
      } catch (IOException ignored) {} 
     } 
    } 
} 

private String load(String fileName) { 
    String res = null; 
    File file = new File(getAppRootDir(), fileName); 
    if(!file.exists()){ 
     Log.e("", "file " +file.getAbsolutePath()+ " not found"); 
     return null; 
    } 
    FileInputStream fis = null; 
    BufferedReader inputReader = null; 
    try { 
     fis = new FileInputStream(file); 
     inputReader = new BufferedReader(new InputStreamReader(fis, "UTF-8")); 
     StringBuilder strBuilder = new StringBuilder(); 
     String line; 
     while ((line = inputReader.readLine()) != null) { 
      strBuilder.append(line + "\n"); 
     } 
     res = strBuilder.toString(); 
    } catch(Throwable e){ 
     if(fis!=null){ 
      try { 
       fis.close(); 
      } catch (IOException ignored) {} 
     } 
     if(inputReader!= null){ 
      try { 
       inputReader.close(); 
      } catch (IOException ignored) {} 
     } 
    } 
    return res; 
} 

public File getAppRootDir() { 
    File appRootDir; 
    boolean externalStorageAvailable; 
    boolean externalStorageWriteable; 
    String state = Environment.getExternalStorageState(); 
    if (Environment.MEDIA_MOUNTED.equals(state)) { 
     externalStorageAvailable = externalStorageWriteable = true; 
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { 
     externalStorageAvailable = true; 
     externalStorageWriteable = false; 
    } else { 
     externalStorageAvailable = externalStorageWriteable = false; 
    } 
    if (externalStorageAvailable && externalStorageWriteable) { 
     appRootDir = getExternalFilesDir(null); 
    } else { 
     appRootDir = getDir("appRootDir", MODE_PRIVATE); 
    } 
    if (!appRootDir.exists()) { 
     appRootDir.mkdir(); 
    } 
    return appRootDir; 
} 
+0

Я установил это, чтобы сказать, где показать текст try { \t \t \t \t JSONArray jArray = new JSONArray (res); \t \t \t \t String storyNames = ""; \t \t \t \t для (INT I = 0; г daniel

+0

Неправильное ли место? После \t res = strBuilder.toString(); – daniel

Смежные вопросы