php - 当互联网消失时,如何将数据从mysql下载到android

标签 php android mysql storage internal

我的应用程序在 mysql 和 android 中完美运行,我的问题是当互联网关闭时,可视化以前不再显示的信息。有什么方法可以将信息保存在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);
}

}

最佳答案

使用手机中的 SQLite 数据库来存储从 MySQL 数据库服务器获取的内容。您的应用应该仅在需要时更新内容(用户点击刷新内容已过时)并且有互联网连接。

关于php - 当互联网消失时,如何将数据从mysql下载到android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21732789/

相关文章:

java - API 22 相机按 Intent 发布

Android 应用程序当前 Activity 问题

mysql - 使用 UNION ALL 和 ORDER BY 优化查询

php - JOINS 与 while 语句

PHP preg_match_all 匹配多种模式

Android - 3 次滑动后 Sherlock 内容消失

php - 如何让 PhpMyAdmin 删除/截断而不要求确认

PHP 在文件中写入制表符?

javascript - 在 Question2Answer 中特定帖子的第 n 段后添加 javascript

mysql - Prestashop 从查询中添加类别