0

I have my app working perfectly in mysql and android, my problem is that when the internet is off visualize information that is no longer displayed before. there any way to save the information in the internal memory of android.

public class ListBioEscanerHuella extends Activity{
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listaproducto);

    // Permission StrictMode
    if (android.os.Build.VERSION.SDK_INT > 11) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    }

    // listView1
    final ListView lstView1 = (ListView)findViewById(R.id.listView1);

    String url = "http://www.miapp.com/androidapp/info/miphp.php";

    try {
    JSONArray data = new JSONArray(getJSONUrl(url));

    final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
    HashMap<String, String> map;

    for(int i = 0; i < data.length(); i++){
    JSONObject c = data.getJSONObject(i);
    map = new HashMap<String, String>();
    map.put("ImageID", c.getString("ImageID"));
    map.put("ImageDesc", c.getString("ImageDesc"));
    map.put("ImagePath", c.getString("ImagePath"));
    map.put("Desc", c.getString("Desc"));
    MyArrList.add(map);
    }

    lstView1.setAdapter(new ImageAdapter(this,MyArrList));

    final AlertDialog.Builder imageDialog = new AlertDialog.Builder(this);
    final LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);

    // OnClick
    lstView1.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View v,
    int position, long id) {

    View layout = inflater.inflate(R.layout.descripcion_producto,
    (ViewGroup) findViewById(R.id.layout_root));
    ImageView image = (ImageView) layout.findViewById(R.id.fullimage);
    TextView Desc = (TextView) layout.findViewById(R.id.Desc);

    try
    {
    image.setImageBitmap(loadBitmap(MyArrList.get(position).get("ImagePath")));
    Desc.setText(MyArrList.get(position).get("Desc"));
    } catch (Exception e) {
    // When Error
    image.setImageResource(android.R.drawable.ic_menu_report_image);
    }

    //imageDialog.setIcon(android.R.drawable.btn_star_big_on);   
    imageDialog.setTitle(MyArrList.get(position).get("ImageDesc"));
    imageDialog.setView(layout);
    imageDialog.setPositiveButton("Salir", new DialogInterface.OnClickListener(){

    public void onClick(DialogInterface dialog, int which) {
    dialog.dismiss();
    }

    });

    imageDialog.create();
    imageDialog.show();

    }
    });

    } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    //creamos la variable bar para la ejecucion del ActionBar
    ActionBar bar = getActionBar();
    //agrega background al actionbar
    bar.setBackgroundDrawable(getResources().getDrawable(R.drawable.action_barprod));
    //elimina el titulo del actionBar
    bar.setDisplayShowTitleEnabled(false);
    //Bloquea el LandScape del celular para que la app solo sea vertical
    setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

}

public class ImageAdapter extends BaseAdapter
{
        private Context context;
        private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();

        public ImageAdapter(Context c, ArrayList<HashMap<String, String>> list) {
        // TODO Auto-generated method stub
        context = c;
        MyArr = list;
    }

    public int getCount() {
    // TODO Auto-generated method stub
    return MyArr.size();
    }

    public Object getItem(int position) {
    // TODO Auto-generated method stub
    return position;
    }

    public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
    }
    public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub

        LayoutInflater inflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);


        if (convertView == null) {
        convertView = inflater.inflate(R.layout.boton_titulo_producto, null);
        }

        // ColImage
        //ImageView imageView = (ImageView) convertView.findViewById(R.id.ColImgPath);
        //imageView.getLayoutParams().height = 100;
        //imageView.getLayoutParams().width = 100;
        //imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        /*try
        {
        imageView.setImageBitmap(loadBitmap(MyArr.get(position).get("ImagePath")));
        } catch (Exception e) {
        // When Error
        imageView.setImageResource(android.R.drawable.ic_menu_report_image);
        }*/

        // ColPosition
        /*TextView txtPosition = (TextView) convertView.findViewById(R.id.ColImgID);
        txtPosition.setPadding(10, 0, 0, 0);
        txtPosition.setText(MyArr.get(position).get("ImageID"));*/

        // ColPicname
        TextView txtPicName = (TextView) convertView.findViewById(R.id.ColImgDesc);
        txtPicName.setPadding(5, 0, 0, 0);
        txtPicName.setText(MyArr.get(position).get("ImageDesc"));

        return convertView;

    }

}

/*** Get JSON Code from URL ***/
public String getJSONUrl(String url) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Download OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download file..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}

/***** Get Image Resource from URL (Start) *****/
private static final String TAG = "ERROR";
private static final int IO_BUFFER_SIZE = 4 * 1024;
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;

try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();

final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;

bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}

return bitmap;
}

private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
android.util.Log.e(TAG, "Could not close stream", e);
}
}
}

private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}
/***** Get Image Resource from URL (End) *****/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.producto, menu);
    return true;
}
//se despliega en el ActionBar los items de facebook twitter youtube y main todo con un switch
@Override
public boolean onOptionsItemSelected(MenuItem item){
    switch(item.getItemId()){
    case R.id.menu_face:
        startActivity(new Intent(getApplicationContext(), facebook.class));
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
        return true;
    case R.id.menu_twitt:
        startActivity(new Intent(getApplicationContext(), twitter.class));
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
        return true;
    case R.id.menu_yout:
        startActivity(new Intent(getApplicationContext(), youtube.class));
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
        return true;    
    }
    return true;
}

//Metodo para hacer la animacion de regresar la vista (activity) anterior del lado derecho
@Override
public void onBackPressed() {
    super.onBackPressed();
    overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}

}

  • Have a look at SharedPreferences, that could be a solution for you. Or maybe writing to the phones SD card http://stackoverflow.com/a/9306962/993600 – TMH Feb 12 '14 at 15:54
  • thanks Tom i try to understand but not sucesfull – user3302335 Feb 12 '14 at 20:02
  • Wouldn't my suggestion work? Since the content you want to cache is database content, it makes sense to use a database to cache it, rather than use a file or shared preferences. – ADTC Feb 13 '14 at 10:00
  • 1
    @ADTC You solution would probably be and optimal one, I forgot about SQLite (I don't use it often :P). – TMH Feb 13 '14 at 13:12

1 Answers1

1

Use an SQLite database in-phone to store the content you fetch from the MySQL database server. Your app should only update the content when required (user hits refresh or it is stale) and there is Internet connection.

ADTC
  • 8,999
  • 5
  • 68
  • 93