欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

AsyncTask 异步

程序员文章站 2022-03-09 23:28:45
...

MainActivity

public class MainActivity extends AppCompatActivity {

private String mUrl = "https://suggest.taobao.com/sug?code=utf-8&q=%E6%89%8B%E6%9C%BA";
private ListView lv;
private List<List<String>> mList = new ArrayList<>();
private MyAdapter adapter;
private ContentResolver resolver;
private Uri uri;
private int i;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initView();

    adapter = new MyAdapter(MainActivity.this, mList);
    lv.setAdapter(adapter);


    resolver = getContentResolver();
    uri = Uri.parse("content://com.bawei.diyizhoumoni1.provider.provider.MyProvider/user");


    //判断有网没网
    if(isNetworkConnected(MainActivity.this)){
        Cursor cursor = resolver.query(uri, null, null, null, null);
        if(cursor.getCount()==0){
            new MyTask().execute(mUrl);
            Toast.makeText(MainActivity.this,"请求数据",Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(MainActivity.this,"有网,已经请求过数据并且保存到了数据库",Toast.LENGTH_SHORT).show();
            Cursor query = resolver.query(uri, null, null, null, null);
            while (query.moveToNext()){
                String neirong = query.getString(query.getColumnIndex("neirong"));
                mList.add(Collections.singletonList(neirong));
            }
            adapter.setList(mList);
        }
    }else{
        Toast.makeText(MainActivity.this,"没有联网,从数据库请求数据",Toast.LENGTH_SHORT).show();
        Cursor cursorw = resolver.query(uri, null, null, null, null);
        if(cursorw.getCount()==0){
            Toast.makeText(MainActivity.this,"数据库没有数据",Toast.LENGTH_SHORT).show();
        }else {
            while (cursorw.moveToNext()) {
                String neirong = cursorw.getString(cursorw.getColumnIndex("neirong"));
                mList.add(Collections.singletonList(neirong));
            }
            adapter.setList(mList);
        }
    }

	//条目长点击事件
    lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
            AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("这是标题");
            builder.setMessage("确认要删除吗?");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                        resolver.delete(uri, "neirong=?", new String[]{mList.get(position).toString()});
                        Toast.makeText(MainActivity.this,"删除成功",Toast.LENGTH_SHORT).show();
                        mList.remove(position);
                        adapter.notifyDataSetChanged();




                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            AlertDialog d = builder.create();
            d.show();
            return false;
        }
    });

}


private void initView() {
    lv = findViewById(R.id.Show_lv);
}

class MyTask extends AsyncTask<String, View, List<List<String>>> {

    @Override
    protected List<List<String>> doInBackground(String... strings) {
        try {
            URL url = new URL(strings[0]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            if (connection.getResponseCode() == 200) {
                InputStream stream = connection.getInputStream();
                String getstr = getstr(stream);
                Gson gson = new Gson();
                MyData myData = gson.fromJson(getstr, MyData.class);
              //  Log.d("aaa",myData.toString());
                mList=myData.getResult();
                for (int i=0;i<mList.size();i++){
                    ContentValues values=new ContentValues();
                    values.put("neirong",mList.get(i).toString());
                    resolver.insert(uri,values);
                }
                return mList;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(List<List<String>> lists) {
        super.onPostExecute(lists);
        adapter.setList((List<List<String>>) lists);
    }
}

public boolean isNetworkConnected(Context context) {
    if (context != null) {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (mNetworkInfo != null) {
            return mNetworkInfo.isAvailable();
        }
    }
    return false;
}
//转换
private String getstr(InputStream stream) throws IOException {
    BufferedReader bf = new BufferedReader(new InputStreamReader(stream));
    StringBuffer buffer = new StringBuffer();
    String con = null;
    while ((con = bf.readLine()) != null) {
        buffer.append(con);
    }
    return buffer.toString();
}

}

//适配器
package com.bawei.diyizhoumoni1.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.bawei.diyizhoumoni1.R;

import java.util.List;

public class MyAdapter extends BaseAdapter {
private Context mContext;
private List<List> mList;

public MyAdapter(Context mContext, List<List<String>> mList) {
    this.mContext = mContext;
    this.mList = mList;
}

public void setList (List<List<String>> list){
    this.mList=list;
    notifyDataSetChanged();
}


@Override
public int getCount() {

    return mList.size();
}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if(convertView==null){
        convertView=View.inflate(mContext, R.layout.list_item,null);
        holder=new ViewHolder();
        holder.tv=convertView.findViewById(R.id.Text_tv);
        convertView.setTag(holder);
    }else{
        holder=(ViewHolder)convertView.getTag();
    }
    holder.tv.setText(mList.get(position).toString());

    return convertView;
}
class ViewHolder{
    TextView tv;
}

}

//数据库
package com.bawei.diyizhoumoni1.helper;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MyHelper extends SQLiteOpenHelper {
public MyHelper(Context context) {
super(context, “BBB”, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {

    String sql="create table if not exists user(uid integer primary key autoincrement,neirong text)";
    db.execSQL(sql);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

}

//增删该查
package com.bawei.diyizhoumoni1.provider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

import com.bawei.diyizhoumoni1.helper.MyHelper;

public class MyProvider extends ContentProvider {

private int i;
private static UriMatcher um=new UriMatcher(UriMatcher.NO_MATCH);
static {
    um.addURI("com.bawei.diyizhoumoni1.provider.provider.MyProvider","user",100);
}
private SQLiteDatabase db;

@Override
public boolean onCreate() {
    MyHelper helper = new MyHelper(getContext());
    db = helper.getWritableDatabase();
    return false;
}

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    Cursor cursor = db.query("user", null, null, null, null, null, null);
    return cursor;
}

@Override
public String getType(Uri uri) {
    return null;
}

@Override
public Uri insert(Uri uri, ContentValues values) {
    switch (um.match(uri)){
        case 100:
            db.insert("user",null,values);
            break;
    }
    return null;
}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
    switch (um.match(uri)){
        case 100:
            i = db.delete("user", selection, selectionArgs);

            break;
    }
    return i;
}

@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    return 0;
}

}

//清单文件

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <provider
        android:authorities="com.bawei.diyizhoumoni1.provider.provider.MyProvider"
        android:name="com.bawei.diyizhoumoni1.provider.MyProvider"
        android:exported="true"></provider>
</application>

仅供参考!!!

相关标签: 异步