JSON_SQLite_Listview06-17

package com.example.ex_day00;

创新互联公司主要从事网站建设、成都做网站、网页设计、企业做网站、公司建网站等业务。立足成都服务邻水,10年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:18980820575

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 = new ArrayList();

MyAsyncTask myAsyncTask;

ListView listview;

    HashMap hashBit = new HashMap();

    HashMap myasync = new HashMap();

    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 p_w_picpathpath_index = query.getColumnIndex("p_w_picpathpath");

           String name = query.getString(name_index);

           String desc = query.getString(desc_index);

           String p_w_picpathpath = query.getString(p_w_picpathpath_index);

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

           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 {

@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

    {

@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 p_w_picpathpath = jsonObject.getString("p_w_picpathpath");

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

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("p_w_picpathpath", ruanjian.p_w_picpathpath);

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

}

   

    }

class MyAsyncTask2 extends AsyncTask {

private ImageView p_w_picpathview;

        int position;

        String name;

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

this.p_w_picpathview = p_w_picpathview;

            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 p_w_picpath_path = cursor.getString(cursor.getColumnIndex("p_w_picpathpath"));

File file = new File(p_w_picpath_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 p_w_picpath_index = params[0].lastIndexOf("/");

String p_w_picpath_path = params[0].substring(p_w_picpath_index);

                if (bitmap!=null) {

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

                String path = Environment.getExternalStorageDirectory().getPath() + "/p_w_picpaths/"+p_w_picpath_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("p_w_picpathpath", path);

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

}

@Override

protected void onPostExecute(Bitmap result) {

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

{

p_w_picpathview.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.p_w_picpathview = (ImageView) inflate.findViewById(R.id.p_w_picpathView1);

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.p_w_picpathview.setImageResource(R.drawable.ic_launcher);

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

if (bitmap == null) {

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

if(task2==null)

{

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

   myasync.put(ruanJian2.p_w_picpathpath, task2);

   task2.execute(ruanJian2.p_w_picpathpath);

}

}else

{

user.p_w_picpathview.setImageBitmap(bitmap);

}

return inflate;

}

}

    class User

    {

    ImageView p_w_picpathview;

    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_Listview06-17
链接地址:http://scyanting.com/article/ppcicg.html