1

我为离线概念创建了一个 android 应用程序。当互联网连接的数据可以通过服务器同步时。

我的平板电脑有超过 5.7GB 的存储空间作为内部存储器。当我从服务器同步数据时,它报告错误为内存不足。

我认为数据存储位置已更改,它存储在其他位置。任何人都可以解决这个问题吗?我认为要在清单文件中进行一些修改。

我的同步码

public class sync extends Activity implements OnClickListener {
private static String url = "Json URL";
// Button
Button chktosync, logout_menu;
private ProgressDialog pd;
DBAdapter db = new DBAdapter(this);
JSONArray contacts = null;
JSONArray cropdetails = null;
JSONArray biodetails = null;
String land, area, sf, land_id;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sync);
    logout_menu = (Button) findViewById(R.id.logout_menu);
    logout_menu.setOnClickListener(this);
    chktosync = (Button) findViewById(R.id.chktosync);
    chktosync.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
        pd = ProgressDialog.show(sync.this, "Synchronizing", "Synchronizing...");
        new Thread() {
        public void run() {
        try {
            processThread();
            pestanddisease();
            bioparam();
        } catch (Exception e) {
        Log.e("tag", e.getMessage());
        }
        // dismiss the progress dialog
    pd.dismiss();
}
        }.start();
    }
    });
}
private void processThread() {

// Creating JSON Parser instance
JSONParser jParser = new JSONParser();

// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
    // Getting Array of Contacts
    contacts = json.getJSONArray(loginPage.code);
    db.open();
    // looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {

    JSONObject c = contacts.getJSONObject(i);
    // Storing each json item in variable
    String farmerid = c.getString("farmerid");
    String farmername = c.getString("farmername");
    String farmer_fathername = c.getString("farmer_fathername");
    String farmer_mobilenumber = c.getString("farmer_mobilenumber");
    String districtname = c.getString("districtname");
    String blockname = c.getString("blockname");
    String villagename = c.getString("villagename");

    db.insertFarmer(farmerid, farmername,
            farmer_fathername, farmer_mobilenumber,
            districtname, blockname, villagename);
    //land details
    JSONArray Land = c.getJSONArray("land_details");
            for (int l = 0; l < Land.length(); l++) {
        JSONObject s = Land.getJSONObject(l);
        String survey_no = s.getString("survey_no");
        String area  = s.getString("area");
        String land_type = s.getString("land_type");
        String patternref = s.getString("patternref");
        String crop_matrix_id = s.getString("crop_matrix");
        land_id = s.getString("land_id");
        String season1_crop = s.getString("season1_crop");
        String season2_crop = s.getString("season2_crop");
        String season3_crop = s.getString("season3_crop");
        db.insertlanddetails(farmerid, survey_no, area, land_type, patternref, land_id, crop_matrix_id, season1_crop, season2_crop, season3_crop);
}
db.close();
  } 
catch (JSONException e)
 {
   e.printStackTrace();
   }
}


   public void pestanddisease()
     {
         /// Creating JSON Parser instance
         JSONParser jParser = new JSONParser();
        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(pestdisease);
    try    
    {
    // Getting Array of Contacts
    cropdetails = json.getJSONArray("CropDetails");
    db.open();
    for (int i = 0; i < cropdetails.length(); i++) {
    JSONObject s = cropdetails.getJSONObject(i);
    String cropname = s.getString("crop");
    String pest = s.getString("pest_name");
    String disease = s.getString("disease_name");
    db.insertcrop_pest_details(cropname, pest);
    db.insertcrop_disease_details(cropname, disease);
}
    db.close();
 }      catch (JSONException e) {
    e.printStackTrace();
    }
  }
}

JSON解析器代码

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();

        is = httpEntity.getContent();


    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    BufferedReader reader;
    try {
         reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),1048576);

        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) 
        {
            line=reader.readLine();
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
         Log.e("JSON", json);   

    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;
    }
}


原木猫

08-28 02:06:59.199: E/dalvikvm-heap(304): Out of memory on a 9513056-byte allocation.

08-28 02:06:59.446: E/AndroidRuntime(304): Uncaught handler: thread Thread-9 exiting due to uncaught exception
08-28 02:06:59.732: E/AndroidRuntime(304): java.lang.OutOfMemoryError
08-28 02:06:59.732: E/AndroidRuntime(304): at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:97)
08-28 02:06:59.732: E/AndroidRuntime(304): at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:131)
08-28 02:06:59.732: E/AndroidRuntime(304): at java.lang.StringBuilder.append(StringBuilder.java:271)
08-28 02:06:59.732: E/AndroidRuntime(304): at java.io.BufferedReader.readLine(BufferedReader.java:413)
08-28 02:06:59.732: E/AndroidRuntime(304): at com.login.JSONParser.getJSONFromUrl(JSONParser.java:55)
08-28 02:06:59.732: E/AndroidRuntime(304): at com.login.sync.processThread(sync.java:76)
08-28 02:06:59.732: E/AndroidRuntime(304): at com.login.sync.access$1(sync.java:70)
08-28 02:06:59.732: E/AndroidRuntime(304): at com.login.sync$1$1.run(sync.java:57)
08-28 02:07:00.416: I/dalvikvm(304): threadid=7: reacting to signal 3
08-28 02:07:00.416: E/dalvikvm(304): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
4

2 回答 2

0

因此OutOfMemoryError,这并不意味着您的文件系统容量不足,这意味着您的下载缓冲区内存不足。

在您的情况下,您需要更改JSONObject.getJSONFromUrl(URL)管理文件系统上的下载缓冲区而不是内存。这是示例:

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpUriRequest request = new HttpGet(url);
HttpResponse response = httpClient.execute(request);

HttpEntity resEntity = response.getEntity();
InputStream is = null;
FileOutputStream fos = null;

try {
    if (resEntity == null)
        throw new IllegalArgumentException("HTTP entity should not be null.");

    is = resEntity.getContent();
    if (is == null) return 0;

    // Create parent folder to avoid IOException
    if (!mBinaryFile.getParentFile().exists())
        mBinaryFile.getParentFile().mkdirs();

    fos = new FileOutputStream(mBinaryFile, mDownloadedLength!=0);

        byte[] tmp = new byte[8192];
        int bufLength;
        while((bufLength = is.read(tmp)) != -1) {
            fos.write(tmp, 0, bufLength);
        }

    return mBinaryFile.length();

} catch (IOException e) {
    throw new ServerConnectionException(R.string.error_network_error,
            "Download file "+mBinaryFile.getName()+" failed.", e);
} finally {
    Utils.closeStream(is);
    Utils.closeStream(fos);
}

在这种情况下,只需要 8KB 内存,就可以解决您的 OOM 问题。但是您的问题将转向如何从文件系统中读取 JSON 数据。只需逐个读取您需要的数据以避免OutOfMemoryError,并在完成后立即释放内存。

于 2012-08-28T06:58:07.710 回答
0

Json 解析器工作正常。无需将其更改为文件。错误的原因是 JSON 没有正确出现。我在服务器端做了一些修改。现在它工作正常。同步数据前请确保JSON有效与否。感谢您的支持...

于 2012-09-05T06:41:41.017 回答