首页 > 数据库技术 > 详细

JSON_SQLite_Listview 06-17

时间:2014-06-28 00:33:20      阅读:484      评论:0      收藏:0      [点我收藏+]

package com.example.ex_day00;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLConnection;

import java.nio.ByteBuffer;

import java.util.ArrayList;

import java.util.HashMap;

import org.apache.http.util.ByteArrayBuffer;

import org.apache.http.util.EncodingUtils;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

import android.os.AsyncTask;

import android.os.Bundle;

import android.os.Environment;

import android.app.Activity;

import android.content.ContentValues;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.transition.Visibility;

import android.util.Log;

import android.view.LayoutInflater;

import android.view.Menu;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.ViewGroup;

import android.widget.BaseAdapter;

import android.widget.Button;

import android.widget.EditText;

import android.widget.ImageView;

import android.widget.ListView;

import android.widget.ProgressBar;

public class MainActivity extends Activity implements OnClickListener {

String path = "http://10.0.2.2:8080/abc.txt";

ArrayList<RuanJian> ruanjian = new ArrayList<RuanJian>();

MyAsyncTask myAsyncTask;

ListView listview;

    HashMap<String, Bitmap> hashBit = new HashMap<String,Bitmap>();

    HashMap<String,MyAsyncTask2> myasync = new HashMap<String,MyAsyncTask2>();

    EditText chongshi;

    ProgressBar progressbar;

    Button button;

private MyAdaper myAdaper;

private SQLiteDatabase mdb;   

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

listview = (ListView) findViewById(R.id.listView1);

progressbar = (ProgressBar)findViewById(R.id.progressBar1);

chongshi = (EditText)findViewById(R.id.chongshi);

   button = (Button)findViewById(R.id.button1);

   button.setOnClickListener(this);

   download();

   selectSQL();


}


private void selectSQL() {

ruanjian.clear();

        Cursor query = mdb.query("student", null, null, null, null, null, null);

        boolean toFirst = query.moveToFirst();

        while (toFirst) {

           int name_index = query.getColumnIndex("name");

           int desc_index = query.getColumnIndex("desc");

           int imagepath_index = query.getColumnIndex("imagepath");

           String name = query.getString(name_index);

           String desc = query.getString(desc_index);

           String imagepath = query.getString(imagepath_index);

           ruanjian.add(new RuanJian(name, desc, imagepath));

           toFirst = query.moveToNext();

}

        myAdaper.notifyDataSetChanged();

}


private void LianJieSQL() {

      MyData myData = new MyData(this);

      mdb = myData.getReadableDatabase();

}


private void download() {

MyAsyncTask myAsyncTask = new MyAsyncTask();

myAsyncTask.execute(path);

LianJieSQL();

myAdaper = new MyAdaper();

listview.setAdapter(myAdaper);

}


class MyAsyncTask extends AsyncTask<String, String, String> {


@Override

protected String doInBackground(String... params) {

                 ByteArrayBuffer arrayBuffer = new ByteArrayBuffer(50);

try {

URL url = new URL(params[0]);

URLConnection openConnection = url.openConnection();

openConnection.setConnectTimeout(3000);

openConnection.setReadTimeout(3000);

                InputStream inputStream = openConnection.getInputStream();

byte[] buffer = new byte[1024];

int len = 0;

while((len = inputStream.read(buffer)) !=-1)

{

   arrayBuffer.append(buffer, 0, len);

}

}  catch (MalformedURLException e) {

runOnUiThread(new Runnable() {

@Override

public void run() {

                   chongshi.setText("读取失败1");

                         button.setVisibility(Button.VISIBLE);

                         progressbar.setVisibility(View.INVISIBLE);

}

});

e.printStackTrace();

} catch (IOException e) {

runOnUiThread(new Runnable() {

@Override

public void run() {

                    chongshi.setText("网络连接异常1");

                    button.setVisibility(Button.VISIBLE);

                    progressbar.setVisibility(View.INVISIBLE);

}

});

e.printStackTrace();

}

return new String(arrayBuffer.toByteArray());

}

       @Override

    protected void onPostExecute(String result) {

    super.onPostExecute(result);

    new MyAsyncTask3().execute(result);

    }

}

    class MyAsyncTask3 extends AsyncTask<String, Void, Void>

    {


@Override

protected Void doInBackground(String... params) {

try {

JSONArray array = new JSONArray(params[0]);

SQldelete();

   //删除数据库所有数据delete

for (int i = 0; i < array.length(); i++) {

JSONObject jsonObject = array.getJSONObject(i);

String name = jsonObject.getString("name");

String desc = jsonObject.getString("desc");

String imagepath = jsonObject.getString("imagepath");

RuanJian ruanJian = new RuanJian(name, desc, imagepath);

SQLinsert(ruanJian);

ruanjian.add(ruanJian);

}

} catch (JSONException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

runOnUiThread(new  Runnable() {

public void run() {

myAdaper.notifyDataSetChanged();

}

}); return null;

}


private void SQldelete() {

             mdb.delete("student", null, null);

}


private void SQLinsert(RuanJian ruanjian) {

ContentValues values = new ContentValues();

values.put("name", ruanjian.name);

values.put("desc", ruanjian.desc);

values.put("imagepath", ruanjian.imagepath);

mdb.insert("student", null, values);

}

   

    }

class MyAsyncTask2 extends AsyncTask<String, Void, Bitmap> {


private ImageView imageview;

        int position;

        String name;

public MyAsyncTask2(ImageView imageview,int position,String name) {

this.imageview = imageview;

            this.position = position;

   this.name = name;

}


@Override

protected Bitmap doInBackground(String... params) {

Cursor cursor = mdb.query("student", null, "name = ?",new String[]{name}, null, null, null);

if (cursor.moveToFirst()) {

String image_path = cursor.getString(cursor.getColumnIndex("imagepath"));

File file = new File(image_path);

try {

FileInputStream is = new FileInputStream(file);

Bitmap bitmap = BitmapFactory.decodeStream(is);

hashBit.put(params[0], bitmap);

return bitmap;

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

Bitmap bitmap = null;

try {

URL url = new URL(params[0]);

URLConnection openConnection = url.openConnection();

openConnection.setConnectTimeout(3000);

openConnection.setReadTimeout(3000);

InputStream is = openConnection.getInputStream();

bitmap = BitmapFactory.decodeStream(is);

hashBit.put(params[0], bitmap);

//实现把图片保存到sdcard中

//判断sdcard是否可用

//得到保存图片的上一级目录,file.getparentFile

//bitmap.compress

int image_index = params[0].lastIndexOf("/");

String image_path = params[0].substring(image_index);

                if (bitmap!=null) {

                if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {

                String path = Environment.getExternalStorageDirectory().getPath() + "/images/"+image_path;

                update(path,name);

                File file = new File(path);

                File file2 = file.getParentFile();

                if(!file2.exists())

                {

                file2.mkdirs();

                }

                FileOutputStream fos = new FileOutputStream(file);

                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);

                }

}

} catch (MalformedURLException e) {

runOnUiThread(new Runnable() {

@Override

public void run() {

                   chongshi.setText("读取失败2");

}

});

e.printStackTrace();

} catch (Exception e) {

                   runOnUiThread(new Runnable() {

@Override

public void run() {

                    chongshi.setText("网络连接异常2");

}

});

e.printStackTrace();

}

return bitmap;

}

private void update(String path,String name) {

Log.e("========name========", name+","+path);

ContentValues values = new ContentValues();

values.put("imagepath", path);

mdb.update("student", values , "name =?", new String[]{name});

}

@Override

protected void onPostExecute(Bitmap result) {

if (listview.getFirstVisiblePosition()<=position &&listview.getLastVisiblePosition()>=position) 

{

imageview.setImageBitmap(result);

}

progressbar.setVisibility(ProgressBar.GONE);

chongshi.setVisibility(EditText.GONE);

super.onPostExecute(result);

}

}


class MyAdaper extends BaseAdapter {

@Override

public int getCount() {

// TODO Auto-generated method stub

return ruanjian.size();

}

@Override

public Object getItem(int position) {

// TODO Auto-generated method stub

return null;

}

@Override

public long getItemId(int position) {

// TODO Auto-generated method stub

return 0;

}

@Override

public View getView(int position, View convertView, ViewGroup parent) {

RuanJian ruanJian2 = ruanjian.get(position);

LayoutInflater layoutInflater = getLayoutInflater();

View inflate = null;

User user = new User();

if (convertView==null) {

inflate = layoutInflater.inflate(R.layout.itemp, null);

user.imageview = (ImageView) inflate.findViewById(R.id.imageView1);

user.et1 = (EditText) inflate.findViewById(R.id.editText1);

user.et2 = (EditText) inflate.findViewById(R.id.editText2);

inflate.setTag(user);

}else

{

inflate = convertView;

user = (User)inflate.getTag();

}

user.et1.setText(ruanJian2.name);

user.et2.setText(ruanJian2.desc);

user.imageview.setImageResource(R.drawable.ic_launcher);

Bitmap bitmap = hashBit.get(ruanJian2.imagepath);

if (bitmap == null) {

MyAsyncTask2 task2 = myasync.get(ruanJian2.imagepath);

if(task2==null)

{

task2 = new MyAsyncTask2(user.imageview,position,ruanJian2.name);

   myasync.put(ruanJian2.imagepath, task2);

   task2.execute(ruanJian2.imagepath);

}

}else

{

user.imageview.setImageBitmap(bitmap);

}

return inflate;

}

}

    class User

    {

    ImageView imageview;

    EditText et1;

    EditText et2;

    }

@Override

public boolean onCreateOptionsMenu(Menu menu) {

getMenuInflater().inflate(R.menu.main, menu);

return true;

}


@Override

public void onClick(View v) {


switch (v.getId()) {

case R.id.button1:

btn_01();

break;


default:

break;

}

}

private void btn_01() {

           download();

           button.setVisibility(Button.INVISIBLE);

           progressbar.setVisibility(ProgressBar.VISIBLE);

           chongshi.setText("正在加载");

}

}


JSON_SQLite_Listview 06-17,布布扣,bubuko.com

JSON_SQLite_Listview 06-17

原文:http://8988940.blog.51cto.com/8978940/1431668

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!