code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/***************************************
*
* Android Bluetooth Oscilloscope
* yus - projectproto.blogspot.com
* September 2010
*
***************************************/
package org.projectproto.yuscope;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class WaveformView extends SurfaceView implements SurfaceHolder.Callback{
// plot area size
private final static int WIDTH = 320;
private final static int HEIGHT = 240;
private static int[] ch1_data = new int[WIDTH];
private static int[] ch2_data = new int[WIDTH];
private static int ch1_pos = 100; //HEIGHT/2;
private static int ch2_pos = 140; //HEIGHT/2;
private WaveformPlotThread plot_thread;
private Paint ch1_color = new Paint();
private Paint ch2_color = new Paint();
private Paint grid_paint = new Paint();
private Paint cross_paint = new Paint();
private Paint outline_paint = new Paint();
public WaveformView(Context context, AttributeSet attrs){
super(context, attrs);
getHolder().addCallback(this);
// initial values
for(int x=0; x<WIDTH; x++){
ch1_data[x] = ch1_pos;
ch2_data[x] = ch2_pos;
}
plot_thread = new WaveformPlotThread(getHolder(), this);
ch1_color.setColor(Color.YELLOW);
ch2_color.setColor(Color.RED);
grid_paint.setColor(Color.rgb(100, 100, 100));
cross_paint.setColor(Color.rgb(70, 100, 70));
outline_paint.setColor(Color.GREEN);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){
}
@Override
public void surfaceCreated(SurfaceHolder holder){
plot_thread.setRunning(true);
plot_thread.start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder){
boolean retry = true;
plot_thread.setRunning(false);
while (retry){
try{
plot_thread.join();
retry = false;
}catch(InterruptedException e){
}
}
}
@Override
public void onDraw(Canvas canvas){
PlotPoints(canvas);
}
public void set_data(int[] data1, int[] data2 ){
plot_thread.setRunning(false);
for(int x=0; x<WIDTH; x++){
// channel 1
if(x<(data1.length)){
ch1_data[x] = HEIGHT-data1[x]+1;
}else{
ch1_data[x] = ch1_pos;
}
// channel 2
if(x<(data1.length)){
ch2_data[x] = HEIGHT-data2[x]+1;
}else{
ch2_data[x] = ch2_pos;
}
}
plot_thread.setRunning(true);
}
public void PlotPoints(Canvas canvas){
// clear screen
canvas.drawColor(Color.rgb(20, 20, 20));
// draw vertical grids
for(int vertical = 1; vertical<10; vertical++){
canvas.drawLine(
vertical*(WIDTH/10)+1, 1,
vertical*(WIDTH/10)+1, HEIGHT+1,
grid_paint);
}
// draw horizontal grids
for(int horizontal = 1; horizontal<10; horizontal++){
canvas.drawLine(
1, horizontal*(HEIGHT/10)+1,
WIDTH+1, horizontal*(HEIGHT/10)+1,
grid_paint);
}
// draw outline
canvas.drawLine(0, 0, (WIDTH+1), 0, outline_paint); // top
canvas.drawLine((WIDTH+1), 0, (WIDTH+1), (HEIGHT+1), outline_paint); //right
canvas.drawLine(0, (HEIGHT+1), (WIDTH+1), (HEIGHT+1), outline_paint); // bottom
canvas.drawLine(0, 0, 0, (HEIGHT+1), outline_paint); //left
// plot data
for(int x=0; x<(WIDTH-1); x++){
canvas.drawLine(x+1, ch2_data[x], x+2, ch2_data[x+1], ch2_color);
canvas.drawLine(x+1, ch1_data[x], x+2, ch1_data[x+1], ch1_color);
}
}
}
| Java |
/*
Author: Alberto Gil Tesa
WebSite: http://giltesa.com
License: CC BY-NC-SA 3.0
http://goo.gl/CTYnN
Project: Task Calendar
Package: com.giltesa.taskcalendar.activity
File: /TaskCalendar/src/com/giltesa/taskcalendar/activity/NewTask.java
*/
/*
NOTAS DEL ACTIVITY:
Desde este Activity no se realiza ninguna modificacion de las tareas. Simplemente se reciben datos y se devuelven.
Sera el padre, es decir el que llamo a esta tarea, el que se encargue de hacer lo que convenga con esos datos.
Por ejemplo, si es el Activity Main quien abre un NewTask, al hacerlo le enviara los datos, estos pueden ser:
Solo la posicion del tag en la que nos encotrabamos para que aparezca por defecto en el formulario.
O ademas los datos de la tarea si le hemos dado a editar.
En ambos casos cuando se termine esos datos se devolveran al Activity y este hara la insercion, actualizacion o nada.
Esto ha de hacerse asi ya que es la unica forma con la que he sabido refrescar despues la pantalla principal (o la del Activity padre)
*/
package com.giltesa.taskcalendar.activity;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.giltesa.taskcalendar.R;
import com.giltesa.taskcalendar.adapter.TagArrayListAdapter;
import com.giltesa.taskcalendar.helper.PreferenceHelper;
import com.giltesa.taskcalendar.helper.TagHelper;
import com.giltesa.taskcalendar.helper.TaskHelper;
import com.giltesa.taskcalendar.util.Tag;
import com.giltesa.taskcalendar.util.Task;
public class NewTask extends Activity
{
private EditText EditTextTitle;
private EditText EditTextDescription;
private Spinner ListSpinnerTag;
private Bundle dataReceived;
private static TaskHelper taskHelper;
/**
* Al crearse el activity se recuperan todos los controles y se autorellenan si es necesario.
*/
@TargetApi( Build.VERSION_CODES.HONEYCOMB )
@SuppressLint( "NewApi" )
public void onCreate(Bundle savedInstanceState)
{
// Se establece el theme del Activity:
setTheme(new PreferenceHelper(this).getTheme());
super.onCreate(savedInstanceState);
setContentView(R.layout.new_task);
// Activa el icono del ActionBar como boton Return:
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
// Se recuperan los campos del activity:
EditTextTitle = (EditText)findViewById(R.id.main_newtask_title_text);
EditTextDescription = (EditText)findViewById(R.id.main_newtask_description_text);
ListSpinnerTag = (Spinner)findViewById(R.id.main_newtask_tag_spinner);
// Se carga la lista de etiquetas en el Spinner:
ArrayList< Tag > tagArrayList = new TagHelper(this).getTagArrayList();
TagArrayListAdapter tagArrayListAdapter = new TagArrayListAdapter(this, R.layout.settings_tags_listitem_spinner, tagArrayList);
ListSpinnerTag.setAdapter(tagArrayListAdapter);
// Al construirse el activity hay que preconfigurar el formulario segun si le hemos dado a "Nueva tarea" o a "Editar tarea".
dataReceived = getIntent().getBundleExtra("dataActivity");
// En ambos casos se autoselecciona el item del Spinner para que coincida con la ultima pagina vista:
ListSpinnerTag.setSelection(dataReceived.getInt("positionSlider"));
// Ademas si le hemos dado a "Editar Tarea" se mostrara la informacion que ya contuviera la tarea:
if( !dataReceived.getBoolean("isNewTask") )
{
EditTextTitle.setText(dataReceived.getString("title"));
EditTextDescription.setText(dataReceived.getString("description"));
}
taskHelper = new TaskHelper(this);
}
/**
* Se carga el ActionBar en el activity
*/
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.new_task_actionbar, menu);
return true;
}
/**
* Se tratan los eventos de los botones del ActionBar
*/
@SuppressLint( "SimpleDateFormat" )
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch( item.getItemId() )
{
case android.R.id.home:
setResult(Main.BACK, null);
finish();
break;
case R.id.main_newtask_actionbar_save:
if( EditTextTitle.getText().length() == 0 )
{
Toast.makeText(this, getString(R.string.main_newtask_requeridFields), Toast.LENGTH_LONG).show();
}
else
{
Intent intent = new Intent(this, Main.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Bundle dataReturned = new Bundle();
dataReturned.putInt("positionSlider", ListSpinnerTag.getSelectedItemPosition());
intent.putExtra("dataActivity", dataReturned);
Task task = new Task(dataReceived.getInt("id"), ( (Tag)ListSpinnerTag.getSelectedItem() ).getID(), null, EditTextTitle.getText().toString(), EditTextDescription.getText().toString(), null);
if( dataReceived.getBoolean("isNewTask") )
{
taskHelper.insertTask(task);
Toast.makeText(this, getString(R.string.main_newtask_taskInserted), Toast.LENGTH_LONG).show();
}
else
{
taskHelper.updateTask(task);
Toast.makeText(this, getString(R.string.main_newtask_taskUpdated), Toast.LENGTH_LONG).show();
}
startActivity(intent);
}
break;
default:
break;
}
return true;
}
}
| Java |
/*
Author: Alberto Gil Tesa
WebSite: http://giltesa.com
License: CC BY-NC-SA 3.0
http://goo.gl/CTYnN
Project: Task Calendar
Package: com.giltesa.taskcalendar.activity
File: /TaskCalendar/src/com/giltesa/taskcalendar/activity/SettingsAbout.java
*/
package com.giltesa.taskcalendar.activity;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import com.giltesa.taskcalendar.R;
import com.giltesa.taskcalendar.helper.PreferenceHelper;
public class SettingsAbout extends Activity implements OnClickListener
{
protected PreferenceHelper prefs;
/**
*
*/
@TargetApi( Build.VERSION_CODES.HONEYCOMB )
@SuppressLint( "NewApi" )
@Override
public void onCreate(Bundle savedInstanceState)
{
prefs = new PreferenceHelper(this);
setTheme(prefs.getTheme());
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_about);
//Permite que el icono de la barra de name se comporte como el boton atras, y su evento sea tratado desde onOptionsItemSelected()
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
TextView version = (TextView)findViewById(R.id.settings_about_version);
version.setText(getString(R.string.about_version) + " " + prefs.getVersionName());
}
/**
*
*/
public void onClick(View view)
{
if( view.getId() == R.id.settings_about_url )
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.about_blog_url))));
}
/**
*
*/
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch( item.getItemId() )
{
case android.R.id.home:
finish();
break;
default:
break;
}
return true;
}
}
| Java |
/*
Author: Alberto Gil Tesa
WebSite: http://giltesa.com
License: CC BY-NC-SA 3.0
http://goo.gl/CTYnN
Project: Task Calendar
Package: com.giltesa.taskcalendar.adapter
File: /TaskCalendar/src/com/giltesa/taskcalendar/taskArrayListAdapter/TagArrayListAdapter.java
Class:
public class TagArrayListAdapter
private class TagViewHolder
*/
package com.giltesa.taskcalendar.adapter;
import java.util.ArrayList;
import android.app.Activity;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.giltesa.taskcalendar.R;
import com.giltesa.taskcalendar.util.Tag;
public class TagArrayListAdapter extends ArrayAdapter< Tag >
{
Activity context;
ArrayList< Tag > tagArrayList;
/**
* @param context
* @param tagArrayList
*/
public TagArrayListAdapter(Activity context, ArrayList< Tag > tagArrayList)
{
super(context, R.layout.settings_tags_listitem, tagArrayList);
this.context = context;
this.tagArrayList = tagArrayList;
}
/**
* @param context
* @param simpleSpinnerItem
* @param tagArrayList
*/
public TagArrayListAdapter(Activity context, int simpleSpinnerItem, ArrayList< Tag > tagArrayList)
{
super(context, simpleSpinnerItem, tagArrayList);
this.context = context;
this.tagArrayList = tagArrayList;
}
/**
*
*/
public View getView(int position, View item, ViewGroup parent)
{
TagViewHolder holder;
if( item == null )
{
LayoutInflater inflater = context.getLayoutInflater();
item = inflater.inflate(R.layout.settings_tags_listitem, null);
holder = new TagViewHolder();
holder.id = (TextView)item.findViewById(R.id.tags_listitem_id);
holder.name = (TextView)item.findViewById(R.id.tags_listitem_name);
holder.color = (TextView)item.findViewById(R.id.tags_listitem_color);
holder.counter = (TextView)item.findViewById(R.id.tags_listitem_counter);
item.setTag(holder);
}
else
{
holder = (TagViewHolder)item.getTag();
}
holder.id.setText(tagArrayList.get(position).getID() + "");
holder.name.setText(tagArrayList.get(position).getName());
holder.color.setBackgroundColor(Color.parseColor(tagArrayList.get(position).getColor()));
holder.counter.setText(tagArrayList.get(position).getCounter() + " " + context.getResources().getString(R.string.settings_tags_task));
return( item );
}
/**
* Clase TagViewHolder
*/
private class TagViewHolder
{
public TextView id;
public TextView name;
public TextView color;
public TextView counter;
}
}
| Java |
/*
Author: Alberto Gil Tesa
WebSite: http://giltesa.com
License: CC BY-NC-SA 3.0
http://goo.gl/CTYnN
Project: Task Calendar
Package: com.giltesa.taskcalendar.adapter
File: /TaskCalendar/src/com/giltesa/taskcalendar/taskArrayListAdapter/TagArrayListAdapter.java
Class:
public class BackupArrayAdapter
private class BackupViewHolder
*/
package com.giltesa.taskcalendar.adapter;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.giltesa.taskcalendar.R;
import com.giltesa.taskcalendar.util.Backup;
public class BackupArrayAdapter extends ArrayAdapter< Backup >
{
Activity context;
Backup[] arrayBackups;
/**
* @param context
* @param backup
*/
public BackupArrayAdapter(Activity context, Backup[] backup)
{
super(context, R.layout.settings_backup_listitem, backup);
this.context = context;
this.arrayBackups = backup;
}
/**
*
*/
public View getView(int position, View item, ViewGroup parent)
{
BackupViewHolder holder;
if( item == null )
{
LayoutInflater inflater = context.getLayoutInflater();
item = inflater.inflate(R.layout.settings_backup_listitem, null);
holder = new BackupViewHolder();
holder.date = (TextView)item.findViewById(R.id.backup_listitem_date);
holder.length = (TextView)item.findViewById(R.id.backup_listitem_length);
item.setTag(holder);
}
else
{
holder = (BackupViewHolder)item.getTag();
}
holder.date.setText(arrayBackups[position].getDate());
holder.length.setText(arrayBackups[position].getLength());
return( item );
}
/**
* Clase TagViewHolder:
*/
private class BackupViewHolder
{
public TextView date;
public TextView length;
}
}
| Java |
/*
Author: Alberto Gil Tesa
WebSite: http://giltesa.com
License: CC BY-NC-SA 3.0
http://goo.gl/CTYnN
Project: Task Calendar
Package: com.giltesa.taskcalendar.adapter
File: /TaskCalendar/src/com/giltesa/taskcalendar/taskArrayListAdapter/TaskArrayListAdapter.java
Class:
public class TaskArrayListAdapter
private class TaskViewHolder
*/
package com.giltesa.taskcalendar.adapter;
import java.util.ArrayList;
import android.app.Activity;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.giltesa.taskcalendar.R;
import com.giltesa.taskcalendar.util.Task;
public class TaskArrayListAdapter extends ArrayAdapter< Task >
{
Activity context;
ArrayList< Task > taskArrayList;
/**
* @param context
* @param tasks
*/
public TaskArrayListAdapter(Activity context, ArrayList< Task > taskArrayList)
{
super(context, R.layout.settings_tags_listitem, taskArrayList);
this.context = context;
this.taskArrayList = taskArrayList;
}
/**
* @param context
* @param simpleSpinnerItem
* @param tasks
*/
public TaskArrayListAdapter(Activity context, int simpleSpinnerItem, ArrayList< Task > taskArrayList)
{
super(context, simpleSpinnerItem, taskArrayList);
this.context = context;
this.taskArrayList = taskArrayList;
}
/**
*
*/
public View getView(int position, View item, ViewGroup parent)
{
TaskViewHolder holder;
if( item == null )
{
LayoutInflater inflater = context.getLayoutInflater();
item = inflater.inflate(R.layout.main_tasks_listitem, null);
holder = new TaskViewHolder();
holder.id = (TextView)item.findViewById(R.id.task_listitem_id);
holder.idTag = (TextView)item.findViewById(R.id.task_listitem_idTag);
holder.date = (TextView)item.findViewById(R.id.task_listitem_date);
holder.title = (TextView)item.findViewById(R.id.task_listitem_title);
holder.description = (TextView)item.findViewById(R.id.task_listitem_description);
holder.color = (TextView)item.findViewById(R.id.task_listitem_color);
item.setTag(holder);
}
else
{
holder = (TaskViewHolder)item.getTag();
}
holder.id.setText(taskArrayList.get(position).getID() + "");
holder.idTag.setText(taskArrayList.get(position).getIDTag() + "");
holder.date.setText(taskArrayList.get(position).getDate());
holder.title.setText(taskArrayList.get(position).getTitle());
holder.description.setText(taskArrayList.get(position).getDescription());
holder.color.setBackgroundColor(Color.parseColor(taskArrayList.get(position).getColor()));
return( item );
}
/**
* Clase TaskViewHolder:
*/
private class TaskViewHolder
{
public TextView id;
public TextView idTag;
public TextView date;
public TextView title;
public TextView description;
public TextView color;
}
}
| Java |
/*
Author: Alberto Gil Tesa
WebSite: http://giltesa.com
License: CC BY-NC-SA 3.0
http://goo.gl/CTYnN
Project: Task Calendar
Package: com.giltesa.taskcalendar.util
File: /TaskCalendar/src/com/giltesa/taskcalendar/helper/PreferenceHelper.java
*/
package com.giltesa.taskcalendar.helper;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.preference.PreferenceManager;
import com.giltesa.taskcalendar.R;
public final class PreferenceHelper
{
private Activity context;
private static final String PREF_SORT = "main_menu_settings_app_sortTasksBy_key";
private static final String PREF_THEME = "main_menu_settings_app_theme_key";
private static final String PREF_EXIT = "main_menu_settings_app_confirmExit_key";
private static final String PREF_DIR = "main_menu_settings_calendar_directoryStorage_key";
//private static final String PREF_ABOUT = "main_menu_settings_about_about_key";
//private static final String PREF_SHARE = "main_menu_settings_about_share_key";
/**
* @param context
*/
public PreferenceHelper(Activity context)
{
this.context = context;
}
/**
* @return
*/
public String getSortTask()
{
String order = PreferenceManager.getDefaultSharedPreferences(context).getString(PREF_SORT, "");
String result = "";
String[] listOrders = context.getResources().getStringArray(R.array.main_menu_settings_app_sortTasksBy_listOptions);
if( order.equals(listOrders[0]) ) // Oldest first
result += "ORDER BY creation_date ASC";
else if( order.equals(listOrders[1]) ) // Newest first
result += "ORDER BY creation_date DESC";
return result;
}
/**
* @return
*/
public int getTheme()
{
String[] listThemes = context.getResources().getStringArray(R.array.main_menu_settings_app_theme_listOptions);
String theme = PreferenceManager.getDefaultSharedPreferences(context).getString(PREF_THEME, "");
if( theme.equals(listThemes[0]) )
return android.R.style.Theme_Holo;
else
return android.R.style.Theme_Holo_Light_DarkActionBar;
}
/**
* @return
*/
public boolean isConfirmExit()
{
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(PREF_EXIT, false);
}
/**
* @return
*/
public String getDirectory()
{
return PreferenceManager.getDefaultSharedPreferences(context).getString(PREF_DIR, context.getResources().getString(R.string.main_menu_settings_calendar_directoryStorage_defaultValue));
}
/**
* @return
*/
public String getVersionName()
{
PackageManager pm = context.getPackageManager();
try
{
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
return pi.versionName;
}
catch( NameNotFoundException e )
{
return "";
}
}
}
| Java |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.giltesa.taskcalendar.util;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
public class ColorPickerDialog extends Dialog
{
public interface OnColorChangedListener
{
void colorChanged(int color);
}
private OnColorChangedListener mListener;
private int mInitialColor;
private static class ColorPickerView extends View
{
private Paint mPaint;
private Paint mCenterPaint;
private final int[] mColors;
private OnColorChangedListener mListener;
ColorPickerView(Context c, OnColorChangedListener l, int color)
{
super(c);
mListener = l;
mColors = new int[] { 0xFFFF0000, 0xFFFF00FF, 0xFF0000FF, 0xFF00FFFF, 0xFF00FF00, 0xFFFFFF00, 0xFFFF0000 };
Shader s = new SweepGradient(0, 0, mColors, null);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setShader(s);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(60);//32
mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mCenterPaint.setColor(color);
mCenterPaint.setStrokeWidth(5);
}
private boolean mTrackingCenter;
private boolean mHighlightCenter;
@SuppressLint( "DrawAllocation" )
@Override
protected void onDraw(Canvas canvas)
{
float r = CENTER_X - mPaint.getStrokeWidth() * 0.5f;
canvas.translate(CENTER_X, CENTER_X);
canvas.drawOval(new RectF(-r, -r, r, r), mPaint);
canvas.drawCircle(0, 0, CENTER_RADIUS, mCenterPaint);
if( mTrackingCenter )
{
int c = mCenterPaint.getColor();
mCenterPaint.setStyle(Paint.Style.STROKE);
if( mHighlightCenter )
{
mCenterPaint.setAlpha(0xFF);
}
else
{
mCenterPaint.setAlpha(0x80);
}
canvas.drawCircle(0, 0, CENTER_RADIUS + mCenterPaint.getStrokeWidth(), mCenterPaint);
mCenterPaint.setStyle(Paint.Style.FILL);
mCenterPaint.setColor(c);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
setMeasuredDimension(CENTER_X * 2, CENTER_Y * 2);
}
private static final int CENTER_X = 150; //100
private static final int CENTER_Y = 150; //100
private static final int CENTER_RADIUS = 60; //32
private int floatToByte(float x)
{
int n = java.lang.Math.round(x);
return n;
}
private int pinToByte(int n)
{
if( n < 0 )
{
n = 0;
}
else if( n > 255 )
{
n = 255;
}
return n;
}
private int ave(int s, int d, float p)
{
return s + java.lang.Math.round(p * ( d - s ));
}
private int interpColor(int colors[], float unit)
{
if( unit <= 0 )
{
return colors[0];
}
if( unit >= 1 )
{
return colors[colors.length - 1];
}
float p = unit * ( colors.length - 1 );
int i = (int)p;
p -= i;
// now p is just the fractional part [0...1) and i is the index
int c0 = colors[i];
int c1 = colors[i + 1];
int a = ave(Color.alpha(c0), Color.alpha(c1), p);
int r = ave(Color.red(c0), Color.red(c1), p);
int g = ave(Color.green(c0), Color.green(c1), p);
int b = ave(Color.blue(c0), Color.blue(c1), p);
return Color.argb(a, r, g, b);
}
@SuppressWarnings( "unused" )
private int rotateColor(int color, float rad)
{
float deg = rad * 180 / 3.1415927f;
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);
ColorMatrix cm = new ColorMatrix();
ColorMatrix tmp = new ColorMatrix();
cm.setRGB2YUV();
tmp.setRotate(0, deg);
cm.postConcat(tmp);
tmp.setYUV2RGB();
cm.postConcat(tmp);
final float[] a = cm.getArray();
int ir = floatToByte(a[0] * r + a[1] * g + a[2] * b);
int ig = floatToByte(a[5] * r + a[6] * g + a[7] * b);
int ib = floatToByte(a[10] * r + a[11] * g + a[12] * b);
return Color.argb(Color.alpha(color), pinToByte(ir), pinToByte(ig), pinToByte(ib));
}
private static final float PI = 3.1415926f;
@Override
public boolean onTouchEvent(MotionEvent event)
{
float x = event.getX() - CENTER_X;
float y = event.getY() - CENTER_Y;
boolean inCenter = java.lang.Math.sqrt(x * x + y * y) <= CENTER_RADIUS;
switch( event.getAction() )
{
case MotionEvent.ACTION_DOWN:
mTrackingCenter = inCenter;
if( inCenter )
{
mHighlightCenter = true;
invalidate();
break;
}
case MotionEvent.ACTION_MOVE:
if( mTrackingCenter )
{
if( mHighlightCenter != inCenter )
{
mHighlightCenter = inCenter;
invalidate();
}
}
else
{
float angle = (float)java.lang.Math.atan2(y, x);
// need to turn angle [-PI ... PI] into unit [0....1]
float unit = angle / ( 2 * PI );
if( unit < 0 )
{
unit += 1;
}
mCenterPaint.setColor(interpColor(mColors, unit));
invalidate();
}
break;
case MotionEvent.ACTION_UP:
if( mTrackingCenter )
{
if( inCenter )
{
mListener.colorChanged(mCenterPaint.getColor());
}
mTrackingCenter = false; // so we draw w/o halo
invalidate();
}
break;
}
return true;
}
}
public ColorPickerDialog(Context context, OnColorChangedListener listener, int initialColor)
{
super(context);
mListener = listener;
mInitialColor = initialColor;
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
OnColorChangedListener l = new OnColorChangedListener()
{
public void colorChanged(int color)
{
mListener.colorChanged(color);
dismiss();
}
};
setContentView(new ColorPickerView(getContext(), l, mInitialColor));
//setTitle("Pick a Color");
}
}
| Java |
/*
Author: Alberto Gil Tesa
WebSite: http://giltesa.com
License: CC BY-NC-SA 3.0
http://goo.gl/CTYnN
Project: Task Calendar
Package: com.giltesa.taskcalendar.util
File: /TaskCalendar/src/com/giltesa/taskcalendar/util/Backup.java
*/
package com.giltesa.taskcalendar.util;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import android.annotation.SuppressLint;
public class Backup
{
private File file;
private String date;
private String length;
/**
* @param file
*/
@SuppressLint( "SimpleDateFormat" )
public Backup(File file)
{
this.file = file;
this.date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(file.lastModified());
this.length = file.length() / Byte.SIZE + " KB";
}
/**
* @param file
* @param modified
* @param size
*/
@SuppressLint( "SimpleDateFormat" )
public Backup(File file, String modified, String size)
{
String[] words = modified.split(" ");
try
{
Date date = new SimpleDateFormat("MMM", Locale.ENGLISH).parse(words[2]);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH) + 1;
words[2] = ( month < 10 ) ? "0" + month : "" + month;
}
catch( ParseException e )
{
e.printStackTrace();
}
this.file = file;
this.date = words[3] + "/" + words[2] + "/" + words[1] + " " + words[4];
this.length = size;
}
public File getFile()
{
return file;
}
public String getDate()
{
return date;
}
public String getLength()
{
return length;
}
}
| Java |
/*
Author: Alberto Gil Tesa
WebSite: http://giltesa.com
License: CC BY-NC-SA 3.0
http://goo.gl/CTYnN
Project: Task Calendar
Package: com.giltesa.taskcalendar.util
File: /TaskCalendar/src/com/giltesa/taskcalendar/util/Tag.java
*/
package com.giltesa.taskcalendar.util;
public class Task
{
private int id;
private int idTag;
private String title;
private String description;
private String date;
private String color;
public Task(int id, int idTag, String date, String title, String description, String color)
{
this.id = id;
this.idTag = idTag;
this.date = date;
this.title = title;
this.description = description;
this.color = color;
}
public int getID()
{
return id;
}
public int getIDTag()
{
return idTag;
}
public String getTitle()
{
return title;
}
public String getDescription()
{
return description;
}
public String getDate()
{
return date;
}
public String getColor()
{
return color;
}
public void setId(int id)
{
this.id = id;
}
public void setIdTag(int idTag)
{
this.idTag = idTag;
}
public void setTitle(String title)
{
this.title = title;
}
public void setDescription(String description)
{
this.description = description;
}
public void setDate(String date)
{
this.date = date;
}
public void setColor(String color)
{
this.color = color;
}
@Override
public String toString()
{
return title;
}
}
| Java |
/*
Author: Alberto Gil Tesa
WebSite: http://giltesa.com
License: CC BY-NC-SA 3.0
http://goo.gl/CTYnN
Project: Task Calendar
Package: com.giltesa.taskcalendar.util
File: /TaskCalendar/src/com/giltesa/taskcalendar/util/Tag.java
*/
package com.giltesa.taskcalendar.util;
public class Tag
{
private int id;
private String name;
private String color;
private int counter;
public Tag(int id, String name, String color, int counter)
{
this.id = id;
this.name = name;
this.color = color;
this.counter = counter;
}
public int getID()
{
return id;
}
public String getName()
{
return name;
}
public String getColor()
{
return color;
}
public int getCounter()
{
return counter;
}
public void setID(int id)
{
this.id = id;
}
public void setName(String name)
{
this.name = name;
}
public void setColor(String color)
{
this.color = color;
}
public void setCounter(int counter)
{
this.counter = counter;
}
public String toString()
{
return name;
}
}
| Java |
/** Automatically generated file. DO NOT MODIFY */
package com.giltesa.taskcalendar;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package java.awt;
/**
*
* @author RUA
*/
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package quanlycuahangcongnghe;
/**
*
* @author RUA
*/
public class ThemLoaiHoaDon extends javax.swing.JFrame {
/**
* Creates new form ThemLoaiHoaDon
*/
public ThemLoaiHoaDon() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextField1.setText("jTextField1");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(156, 156, 156)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(185, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(104, 104, 104)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(176, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ThemLoaiHoaDon.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ThemLoaiHoaDon.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ThemLoaiHoaDon.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ThemLoaiHoaDon.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ThemLoaiHoaDon().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField jTextField1;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package quanlycuahangcongnghe;
import DAO.LoaiHoaDonDAO;
import DAO.NhaCungCapDAO;
import DAO.NhomLoaiSanPhamDAO;
import DAO.PhieuNhapDAO;
import DAO.TimSanPhamDAO;
import DAO.TrangThaiDAO;
import java.util.List;
import java.util.Date;
import org.hibernate.HibernateException;
import java.sql.*;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.table.DefaultTableModel;
import org.hibernate.Query;
import qlchcn.entity.LoaiHoaDon;
import qlchcn.entity.NhaCungCap;
import qlchcn.entity.NhomLoaiSanPham;
import qlchcn.entity.PhieuNhap;
import qlchcn.entity.SanPham;
import qlchcn.entity.TrangThai;
/**
*
* @author RUA
*/
public class Pages extends javax.swing.JFrame {
/**
* Creates new form Pages
*/
public Pages() {
initComponents();
//Thuc hien khi khoi tao form
loadTenNhom();
loadTrangThai();
loadNhaCungCap();
loadLoaiHoaDon();
loadPhieuNhap();
insertPhieuNhap();
loadNhaSanXuat();
loadNhomLoaiSanPham();
loadMenu();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel12 = new javax.swing.JLabel();
jScrollBar1 = new javax.swing.JScrollBar();
jScrollPane5 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
QuanLyCuaHang = new javax.swing.JTabbedPane();
TrangChu = new javax.swing.JPanel();
jButton5 = new javax.swing.JButton();
jLabel9 = new javax.swing.JLabel();
jButton8 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jLabel10 = new javax.swing.JLabel();
jButton9 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jLabel7 = new javax.swing.JLabel();
jButton10 = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
jLabel8 = new javax.swing.JLabel();
jButton11 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton12 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jButton7 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
HoaDon = new javax.swing.JPanel();
jLabel23 = new javax.swing.JLabel();
txtMaHoaDon_HoaDon = new javax.swing.JTextField();
jLabel24 = new javax.swing.JLabel();
txtSoChungTu_HoaDon = new javax.swing.JTextField();
jLabel25 = new javax.swing.JLabel();
spnNgayChungTu_HoaDon = new javax.swing.JSpinner();
jLabel26 = new javax.swing.JLabel();
jLabel28 = new javax.swing.JLabel();
spnNgayTao_HoaDon = new javax.swing.JSpinner();
cboLoaiHoaDon_HoaDon = new javax.swing.JComboBox();
jLabel29 = new javax.swing.JLabel();
jLabel30 = new javax.swing.JLabel();
cboTrangThai_HoaDon = new javax.swing.JComboBox();
jScrollPane3 = new javax.swing.JScrollPane();
txtDienGiai_HoaDon = new javax.swing.JTextArea();
btnTaoHoaDon_HoaDon = new javax.swing.JButton();
btnHuy_HoaDon = new javax.swing.JButton();
btnDanhSachHoaDon_HoaDon = new javax.swing.JButton();
btnThemHoaDon_HoaDon = new javax.swing.JButton();
btnThemTrangThai_HoaDon = new javax.swing.JButton();
jLabel31 = new javax.swing.JLabel();
txtKhachHang_HoaDon1 = new javax.swing.JTextField();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel2 = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
txtKhachHang_HoaDon = new javax.swing.JTextField();
jLabel27 = new javax.swing.JLabel();
cboNhaSanXuat_HoaDon = new javax.swing.JComboBox();
jLabel32 = new javax.swing.JLabel();
jScrollPane4 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
jLabel33 = new javax.swing.JLabel();
jScrollPane6 = new javax.swing.JScrollPane();
jTable2 = new javax.swing.JTable();
jLabel34 = new javax.swing.JLabel();
btnXoaSanPham_HoaDon = new javax.swing.JButton();
cboTrangThai_HoaDon1 = new javax.swing.JComboBox();
jLabel35 = new javax.swing.JLabel();
PhieuNhap = new javax.swing.JPanel();
jLabel14 = new javax.swing.JLabel();
txtMaPhieu_PhieuNhap = new javax.swing.JTextField();
txtSoChungTu_PhieuNhap = new javax.swing.JTextField();
jLabel15 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jLabel17 = new javax.swing.JLabel();
cboLoaiHoaDon_PhieuNhap = new javax.swing.JComboBox();
jLabel18 = new javax.swing.JLabel();
jLabel19 = new javax.swing.JLabel();
cboNhaCungCap_PhieuNhap = new javax.swing.JComboBox();
btnThemLoaiHoaDon_PhieuNhap = new javax.swing.JButton();
jLabel20 = new javax.swing.JLabel();
cboTrangThai_PhieuNhap = new javax.swing.JComboBox();
jScrollPane1 = new javax.swing.JScrollPane();
txtDienGiai_PhieuNhap = new javax.swing.JTextArea();
jLabel21 = new javax.swing.JLabel();
btnThemPhieuNhap_PhieuNhap = new javax.swing.JButton();
btnHuy_PhieuNhap = new javax.swing.JButton();
btnThemTrangThai_PhieuNhap = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
tblPhieuNhap_PhieuNhap = new javax.swing.JTable();
spnNgayNhap_PhieuNhap = new javax.swing.JSpinner();
spnNgayChungTu_PhieuNhap = new javax.swing.JSpinner();
spnNgayTao_PhieuNhap = new javax.swing.JSpinner();
jLabel22 = new javax.swing.JLabel();
btnThemNhaCungCap_PhieuNhap = new javax.swing.JButton();
btnDanhSachPhieuNhap_PhieuNhap = new javax.swing.JButton();
QuyDinh = new javax.swing.JPanel();
TimKiem = new javax.swing.JPanel();
tabTimKiem = new javax.swing.JTabbedPane();
TimHoaDon = new javax.swing.JPanel();
TimPhieuNhap = new javax.swing.JPanel();
jLabel37 = new javax.swing.JLabel();
txtTenSanPham_TimKiem1 = new javax.swing.JTextField();
cboNhomLoaiSanPham_TimKiem1 = new javax.swing.JComboBox();
jLabel39 = new javax.swing.JLabel();
btnTim_TimKiem1 = new javax.swing.JButton();
TimSanPham = new javax.swing.JPanel();
txtTenSanPham = new javax.swing.JTextField();
jLabel36 = new javax.swing.JLabel();
jLabel38 = new javax.swing.JLabel();
cboNhomLoaiSanPham = new javax.swing.JComboBox();
btnTim = new javax.swing.JButton();
jScrollPane7 = new javax.swing.JScrollPane();
tblSanPham = new javax.swing.JTable();
ThongKe = new javax.swing.JPanel();
KhacHang = new javax.swing.JPanel();
LapPhieuThu = new javax.swing.JPanel();
KhuyenMai = new javax.swing.JPanel();
CuaHang = new javax.swing.JPanel();
SanPham = new javax.swing.JPanel();
NhanVien = new javax.swing.JPanel();
TaiKhoan = new javax.swing.JPanel();
jLabel12.setFont(new java.awt.Font("Tahoma", 1, 8)); // NOI18N
jLabel12.setText("NHÂN VIÊN");
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane5.setViewportView(jTable1);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Quản lý Chuỗi cửa hàng Công nghệ cao");
setBackground(new java.awt.Color(255, 255, 255));
setResizable(false);
QuanLyCuaHang.setRequestFocusEnabled(false);
jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quanlycuahangcongnghe/images/Pie-chart-icon.png"))); // NOI18N
jButton5.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jLabel9.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel9.setText("QUẢN LÝ CỬA HÀNG");
jButton8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quanlycuahangcongnghe/images/gift-card-icon.png"))); // NOI18N
jButton8.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton8ActionPerformed(evt);
}
});
jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quanlycuahangcongnghe/images/Search-icon.png"))); // NOI18N
jButton3.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jLabel10.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel10.setText("QUẢN LÝ SẢN PHẨM");
jButton9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quanlycuahangcongnghe/images/office-building-icon.png"))); // NOI18N
jButton9.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton9ActionPerformed(evt);
}
});
jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quanlycuahangcongnghe/images/Settings-Backup-Sync-icon.png"))); // NOI18N
jButton4.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel7.setText("LẬP PHIẾU THU");
jButton10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quanlycuahangcongnghe/images/checklist-icon.png"))); // NOI18N
jButton10.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton10.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton10ActionPerformed(evt);
}
});
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quanlycuahangcongnghe/images/Cash-register-icon.png"))); // NOI18N
jButton1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel8.setText("KHUYẾN MÃI");
jButton11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quanlycuahangcongnghe/images/Settings-icon.png"))); // NOI18N
jButton11.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton11.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton11ActionPerformed(evt);
}
});
jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quanlycuahangcongnghe/images/history-icon.png"))); // NOI18N
jButton2.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton12.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quanlycuahangcongnghe/images/Status-dialog-password-icon.png"))); // NOI18N
jButton12.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton12.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton12ActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel1.setText("QUẢN LÝ HÓA ĐƠN");
jLabel11.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel11.setText("QUẢN LÝ NHÂN VIÊN");
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel2.setText("QUẢN LÝ PHIẾU NHẬP");
jLabel13.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel13.setText("TÀI KHOẢN");
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel3.setText("THAY ĐỔI QUY ĐỊNH");
jButton7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quanlycuahangcongnghe/images/Note-icon.png"))); // NOI18N
jButton7.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton7ActionPerformed(evt);
}
});
jButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quanlycuahangcongnghe/images/Group-Black-Folder-icon.png"))); // NOI18N
jButton6.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton6ActionPerformed(evt);
}
});
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel4.setText("TÌM KIẾM");
jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel6.setText("KHÁCH HÀNG");
jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jLabel5.setText("THỐNG KÊ");
javax.swing.GroupLayout TrangChuLayout = new javax.swing.GroupLayout(TrangChu);
TrangChu.setLayout(TrangChuLayout);
TrangChuLayout.setHorizontalGroup(
TrangChuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(TrangChuLayout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(TrangChuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(TrangChuLayout.createSequentialGroup()
.addGroup(TrangChuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(TrangChuLayout.createSequentialGroup()
.addGroup(TrangChuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(TrangChuLayout.createSequentialGroup()
.addGroup(TrangChuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(TrangChuLayout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jLabel9)))
.addGroup(TrangChuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(TrangChuLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 96, Short.MAX_VALUE)
.addComponent(jLabel10)
.addGap(21, 21, 21))
.addGroup(TrangChuLayout.createSequentialGroup()
.addGap(82, 82, 82)
.addComponent(jButton10, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(TrangChuLayout.createSequentialGroup()
.addGap(37, 37, 37)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(TrangChuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(TrangChuLayout.createSequentialGroup()
.addGap(117, 117, 117)
.addComponent(jLabel7))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, TrangChuLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel11)
.addGap(10, 10, 10))
.addGroup(TrangChuLayout.createSequentialGroup()
.addGap(83, 83, 83)
.addComponent(jButton11, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, TrangChuLayout.createSequentialGroup()
.addGroup(TrangChuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(TrangChuLayout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(jLabel1))
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 82, Short.MAX_VALUE)
.addGroup(TrangChuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(TrangChuLayout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jLabel2))
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(87, 87, 87)
.addGroup(TrangChuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(TrangChuLayout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jLabel3))
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(TrangChuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(TrangChuLayout.createSequentialGroup()
.addGap(77, 77, 77)
.addGroup(TrangChuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, TrangChuLayout.createSequentialGroup()
.addComponent(jLabel4)
.addGap(49, 49, 49))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, TrangChuLayout.createSequentialGroup()
.addComponent(jLabel8)
.addGap(39, 39, 39))))
.addComponent(jButton12, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, TrangChuLayout.createSequentialGroup()
.addComponent(jLabel13)
.addGap(43, 43, 43)))))
.addContainerGap(22, Short.MAX_VALUE))
);
TrangChuLayout.setVerticalGroup(
TrangChuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(TrangChuLayout.createSequentialGroup()
.addGap(23, 23, 23)
.addGroup(TrangChuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(TrangChuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addGap(23, 23, 23)
.addGroup(TrangChuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(TrangChuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(jLabel7)
.addComponent(jLabel8)
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE)
.addGroup(TrangChuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(TrangChuLayout.createSequentialGroup()
.addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel9))
.addGroup(TrangChuLayout.createSequentialGroup()
.addGroup(TrangChuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton11, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton12, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton10, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(TrangChuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel13)
.addComponent(jLabel11)
.addComponent(jLabel10))))
.addContainerGap(66, Short.MAX_VALUE))
);
QuanLyCuaHang.addTab("Trang chủ", TrangChu);
HoaDon.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jLabel23.setText("Mã hóa đơn:");
jLabel24.setText("Số chứng từ:");
jLabel25.setText("Ngày chứng từ:");
spnNgayChungTu_HoaDon.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.DAY_OF_YEAR));
spnNgayChungTu_HoaDon.setToolTipText("");
spnNgayChungTu_HoaDon.setEditor(new javax.swing.JSpinner.DateEditor(spnNgayChungTu_HoaDon, "d/M/y"));
jLabel26.setText("Loại hóa đơn:");
jLabel28.setText("Ngày tạo:");
spnNgayTao_HoaDon.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.DAY_OF_YEAR));
spnNgayTao_HoaDon.setToolTipText("");
spnNgayTao_HoaDon.setEditor(new javax.swing.JSpinner.DateEditor(spnNgayTao_HoaDon, "d/M/y"));
cboLoaiHoaDon_HoaDon.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel29.setText("Trạng thái:");
jLabel30.setText("Diễn giải:");
cboTrangThai_HoaDon.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
txtDienGiai_HoaDon.setColumns(20);
txtDienGiai_HoaDon.setRows(5);
jScrollPane3.setViewportView(txtDienGiai_HoaDon);
btnTaoHoaDon_HoaDon.setText("Khởi tạo");
btnTaoHoaDon_HoaDon.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTaoHoaDon_HoaDonActionPerformed(evt);
}
});
btnHuy_HoaDon.setText("Hủy");
btnHuy_HoaDon.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnHuy_HoaDonActionPerformed(evt);
}
});
btnDanhSachHoaDon_HoaDon.setText("Danh sách");
btnDanhSachHoaDon_HoaDon.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDanhSachHoaDon_HoaDonActionPerformed(evt);
}
});
btnThemHoaDon_HoaDon.setText("+");
btnThemHoaDon_HoaDon.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnThemHoaDon_HoaDonActionPerformed(evt);
}
});
btnThemTrangThai_HoaDon.setText("+");
jLabel31.setText("Nhân viên:");
txtKhachHang_HoaDon1.setEditable(false);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 513, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 136, Short.MAX_VALUE)
);
jTabbedPane1.addTab("Khách hàng cũ", jPanel2);
jLabel27.setText("Khách hàng:");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(7, 7, 7)
.addComponent(jLabel27)
.addGap(18, 18, 18)
.addComponent(txtKhachHang_HoaDon, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(288, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtKhachHang_HoaDon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel27))
.addContainerGap(105, Short.MAX_VALUE))
);
jTabbedPane1.addTab("Thêm khách hàng mới", jPanel1);
cboNhaSanXuat_HoaDon.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel32.setText("Nhà sản xuất:");
jList1.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jScrollPane4.setViewportView(jList1);
jLabel33.setText("Sản phẩm:");
jTable2.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane6.setViewportView(jTable2);
jLabel34.setText("Danh sách sản phẩm được thêm:");
btnXoaSanPham_HoaDon.setText("Xóa");
btnXoaSanPham_HoaDon.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnXoaSanPham_HoaDonActionPerformed(evt);
}
});
cboTrangThai_HoaDon1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel35.setText("Thuế:");
javax.swing.GroupLayout HoaDonLayout = new javax.swing.GroupLayout(HoaDon);
HoaDon.setLayout(HoaDonLayout);
HoaDonLayout.setHorizontalGroup(
HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(HoaDonLayout.createSequentialGroup()
.addContainerGap()
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(HoaDonLayout.createSequentialGroup()
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(HoaDonLayout.createSequentialGroup()
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel25)
.addComponent(jLabel28)
.addComponent(jLabel31)
.addComponent(jLabel32))
.addGap(6, 6, 6))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, HoaDonLayout.createSequentialGroup()
.addComponent(jLabel33)
.addGap(18, 18, 18)))
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane4)
.addComponent(cboNhaSanXuat_HoaDon, 0, 144, Short.MAX_VALUE)
.addComponent(txtKhachHang_HoaDon1)
.addComponent(spnNgayTao_HoaDon)
.addComponent(spnNgayChungTu_HoaDon))
.addGap(18, 18, 18)
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(HoaDonLayout.createSequentialGroup()
.addComponent(jLabel34)
.addGap(0, 441, Short.MAX_VALUE))
.addGroup(HoaDonLayout.createSequentialGroup()
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(btnXoaSanPham_HoaDon)
.addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnTaoHoaDon_HoaDon, javax.swing.GroupLayout.DEFAULT_SIZE, 83, Short.MAX_VALUE)
.addComponent(btnHuy_HoaDon, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))
.addGroup(HoaDonLayout.createSequentialGroup()
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(HoaDonLayout.createSequentialGroup()
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel24)
.addComponent(jLabel23))
.addGap(22, 22, 22)
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtSoChungTu_HoaDon, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtMaHoaDon_HoaDon, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel26)
.addComponent(jLabel29))
.addGap(23, 23, 23)
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cboLoaiHoaDon_HoaDon, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cboTrangThai_HoaDon, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnThemHoaDon_HoaDon)
.addComponent(btnThemTrangThai_HoaDon)))
.addComponent(jTabbedPane1))
.addGap(18, 18, 18)
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3)
.addGroup(HoaDonLayout.createSequentialGroup()
.addComponent(jLabel30)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, HoaDonLayout.createSequentialGroup()
.addComponent(jLabel35)
.addGap(18, 18, 18)
.addComponent(cboTrangThai_HoaDon1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 41, Short.MAX_VALUE)
.addComponent(btnDanhSachHoaDon_HoaDon)))))
.addContainerGap())
);
HoaDonLayout.setVerticalGroup(
HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(HoaDonLayout.createSequentialGroup()
.addContainerGap()
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel26)
.addComponent(cboLoaiHoaDon_HoaDon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnThemHoaDon_HoaDon, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtMaHoaDon_HoaDon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel23))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cboTrangThai_HoaDon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnThemTrangThai_HoaDon, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtSoChungTu_HoaDon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel24)
.addComponent(jLabel29))
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(HoaDonLayout.createSequentialGroup()
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(HoaDonLayout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(HoaDonLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTabbedPane1)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, HoaDonLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel30)
.addGap(153, 153, 153)))
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(spnNgayChungTu_HoaDon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel25))
.addComponent(jLabel34, javax.swing.GroupLayout.Alignment.TRAILING))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(HoaDonLayout.createSequentialGroup()
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(spnNgayTao_HoaDon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel28))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtKhachHang_HoaDon1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel31))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cboNhaSanXuat_HoaDon, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel32))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel33)
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(HoaDonLayout.createSequentialGroup()
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 221, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(HoaDonLayout.createSequentialGroup()
.addGroup(HoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cboTrangThai_HoaDon1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel35)
.addComponent(btnDanhSachHoaDon_HoaDon))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnTaoHoaDon_HoaDon)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnHuy_HoaDon)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnXoaSanPham_HoaDon)))
.addContainerGap(58, Short.MAX_VALUE))
);
QuanLyCuaHang.addTab("Hóa đơn", null, HoaDon, "");
HoaDon.getAccessibleContext().setAccessibleName("");
HoaDon.getAccessibleContext().setAccessibleDescription("");
jLabel14.setText("Mã phiếu:");
txtSoChungTu_PhieuNhap.setToolTipText("");
jLabel15.setText("Số chứng từ:");
jLabel16.setText("Ngày chứng từ:");
jLabel17.setText("Hóa đơn:");
cboLoaiHoaDon_PhieuNhap.setEditable(true);
jLabel18.setText("Ngày nhập:");
jLabel19.setText("Nhà cung cấp:");
cboNhaCungCap_PhieuNhap.setEditable(true);
btnThemLoaiHoaDon_PhieuNhap.setText("+");
jLabel20.setText("Trạng thái:");
txtDienGiai_PhieuNhap.setColumns(20);
txtDienGiai_PhieuNhap.setRows(5);
jScrollPane1.setViewportView(txtDienGiai_PhieuNhap);
jLabel21.setText("Ghi chú:");
btnThemPhieuNhap_PhieuNhap.setText("Tạo phiếu nhập");
btnThemPhieuNhap_PhieuNhap.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnThemPhieuNhap_PhieuNhapActionPerformed(evt);
}
});
btnHuy_PhieuNhap.setText("Hủy");
btnHuy_PhieuNhap.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnHuy_PhieuNhapActionPerformed(evt);
}
});
btnThemTrangThai_PhieuNhap.setText("+");
tblPhieuNhap_PhieuNhap.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null, null}
},
new String [] {
"ID", "Mã phiếu", "Số chứng từ", "Ngày chứng từ", "Ngày nhập", "Ngày tạo", "Loại hóa đơn", "Nhà cung cấp", "Trạng thái", "Người tạo"
}
));
jScrollPane2.setViewportView(tblPhieuNhap_PhieuNhap);
spnNgayNhap_PhieuNhap.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.DAY_OF_YEAR));
spnNgayNhap_PhieuNhap.setEditor(new javax.swing.JSpinner.DateEditor(spnNgayNhap_PhieuNhap, "d/M/y"));
spnNgayChungTu_PhieuNhap.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.DAY_OF_YEAR));
spnNgayChungTu_PhieuNhap.setToolTipText("");
spnNgayChungTu_PhieuNhap.setEditor(new javax.swing.JSpinner.DateEditor(spnNgayChungTu_PhieuNhap, "d/M/y"));
spnNgayTao_PhieuNhap.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.DAY_OF_YEAR));
spnNgayTao_PhieuNhap.setToolTipText("");
spnNgayTao_PhieuNhap.setEditor(new javax.swing.JSpinner.DateEditor(spnNgayTao_PhieuNhap, "d/M/y"));
spnNgayTao_PhieuNhap.setEnabled(false);
jLabel22.setText("Ngày tạo:");
btnThemNhaCungCap_PhieuNhap.setText("+");
btnDanhSachPhieuNhap_PhieuNhap.setText("Danh sách");
btnDanhSachPhieuNhap_PhieuNhap.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDanhSachPhieuNhap_PhieuNhapActionPerformed(evt);
}
});
javax.swing.GroupLayout PhieuNhapLayout = new javax.swing.GroupLayout(PhieuNhap);
PhieuNhap.setLayout(PhieuNhapLayout);
PhieuNhapLayout.setHorizontalGroup(
PhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(PhieuNhapLayout.createSequentialGroup()
.addContainerGap()
.addGroup(PhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(PhieuNhapLayout.createSequentialGroup()
.addGroup(PhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(PhieuNhapLayout.createSequentialGroup()
.addGroup(PhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel14)
.addComponent(jLabel15))
.addGap(23, 23, 23)
.addGroup(PhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtMaPhieu_PhieuNhap, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtSoChungTu_PhieuNhap, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(PhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(PhieuNhapLayout.createSequentialGroup()
.addGroup(PhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(cboLoaiHoaDon_PhieuNhap, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cboTrangThai_PhieuNhap, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(PhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnThemTrangThai_PhieuNhap)
.addComponent(btnThemLoaiHoaDon_PhieuNhap)))
.addGroup(PhieuNhapLayout.createSequentialGroup()
.addGroup(PhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(PhieuNhapLayout.createSequentialGroup()
.addComponent(jLabel18)
.addGap(23, 23, 23)
.addComponent(spnNgayNhap_PhieuNhap, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(PhieuNhapLayout.createSequentialGroup()
.addComponent(jLabel19)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(cboNhaCungCap_PhieuNhap, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnThemNhaCungCap_PhieuNhap))))
.addGroup(PhieuNhapLayout.createSequentialGroup()
.addGroup(PhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(PhieuNhapLayout.createSequentialGroup()
.addComponent(jLabel16)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(spnNgayChungTu_PhieuNhap, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(PhieuNhapLayout.createSequentialGroup()
.addComponent(jLabel22)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(spnNgayTao_PhieuNhap, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(PhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel20)
.addComponent(jLabel17))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 6, Short.MAX_VALUE)
.addComponent(jLabel21)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(PhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PhieuNhapLayout.createSequentialGroup()
.addComponent(btnThemPhieuNhap_PhieuNhap, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnHuy_PhieuNhap)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnDanhSachPhieuNhap_PhieuNhap, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(37, 37, 37))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PhieuNhapLayout.createSequentialGroup()
.addComponent(jScrollPane2)
.addContainerGap())))
);
PhieuNhapLayout.setVerticalGroup(
PhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(PhieuNhapLayout.createSequentialGroup()
.addGap(21, 21, 21)
.addGroup(PhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(PhieuNhapLayout.createSequentialGroup()
.addGroup(PhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel14)
.addComponent(txtMaPhieu_PhieuNhap, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel18)
.addComponent(spnNgayNhap_PhieuNhap, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel21))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(PhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel15)
.addComponent(txtSoChungTu_PhieuNhap, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel19)
.addComponent(cboNhaCungCap_PhieuNhap, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnThemNhaCungCap_PhieuNhap))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(PhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel16)
.addComponent(jLabel20)
.addComponent(cboTrangThai_PhieuNhap, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnThemTrangThai_PhieuNhap)
.addComponent(spnNgayChungTu_PhieuNhap, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(PhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(PhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel17)
.addComponent(spnNgayTao_PhieuNhap, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel22))
.addGroup(PhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnThemPhieuNhap_PhieuNhap)
.addComponent(btnHuy_PhieuNhap)
.addComponent(btnDanhSachPhieuNhap_PhieuNhap))
.addGroup(PhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cboLoaiHoaDon_PhieuNhap, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnThemLoaiHoaDon_PhieuNhap)))
.addGap(18, 18, 18)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE)
.addGap(19, 19, 19))
);
QuanLyCuaHang.addTab("Phiếu nhập", PhieuNhap);
javax.swing.GroupLayout QuyDinhLayout = new javax.swing.GroupLayout(QuyDinh);
QuyDinh.setLayout(QuyDinhLayout);
QuyDinhLayout.setHorizontalGroup(
QuyDinhLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 844, Short.MAX_VALUE)
);
QuyDinhLayout.setVerticalGroup(
QuyDinhLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 574, Short.MAX_VALUE)
);
QuanLyCuaHang.addTab("Quy định", QuyDinh);
javax.swing.GroupLayout TimHoaDonLayout = new javax.swing.GroupLayout(TimHoaDon);
TimHoaDon.setLayout(TimHoaDonLayout);
TimHoaDonLayout.setHorizontalGroup(
TimHoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 819, Short.MAX_VALUE)
);
TimHoaDonLayout.setVerticalGroup(
TimHoaDonLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 524, Short.MAX_VALUE)
);
tabTimKiem.addTab("Tìm Hóa đơn", TimHoaDon);
jLabel37.setText("Tên sản phẩm: ");
jLabel39.setText("Nhóm sản phẩm:");
btnTim_TimKiem1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quanlycuahangcongnghe/images/smaller/Search-icon.png"))); // NOI18N
btnTim_TimKiem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTim_TimKiem1ActionPerformed(evt);
}
});
javax.swing.GroupLayout TimPhieuNhapLayout = new javax.swing.GroupLayout(TimPhieuNhap);
TimPhieuNhap.setLayout(TimPhieuNhapLayout);
TimPhieuNhapLayout.setHorizontalGroup(
TimPhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(TimPhieuNhapLayout.createSequentialGroup()
.addContainerGap()
.addGroup(TimPhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(TimPhieuNhapLayout.createSequentialGroup()
.addGroup(TimPhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel37)
.addComponent(jLabel39))
.addGap(18, 18, 18)
.addGroup(TimPhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cboNhomLoaiSanPham_TimKiem1, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtTenSanPham_TimKiem1, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(btnTim_TimKiem1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(554, Short.MAX_VALUE))
);
TimPhieuNhapLayout.setVerticalGroup(
TimPhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(TimPhieuNhapLayout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(TimPhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtTenSanPham_TimKiem1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel37))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(TimPhieuNhapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cboNhomLoaiSanPham_TimKiem1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel39))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnTim_TimKiem1)
.addContainerGap(383, Short.MAX_VALUE))
);
tabTimKiem.addTab("Tìm Phiếu nhập", TimPhieuNhap);
jLabel36.setText("Tên sản phẩm: ");
jLabel38.setText("Nhóm sản phẩm:");
cboNhomLoaiSanPham.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cboNhomLoaiSanPhamActionPerformed(evt);
}
});
btnTim.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quanlycuahangcongnghe/images/smaller/Search-icon.png"))); // NOI18N
btnTim.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTimActionPerformed(evt);
}
});
tblSanPham.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane7.setViewportView(tblSanPham);
javax.swing.GroupLayout TimSanPhamLayout = new javax.swing.GroupLayout(TimSanPham);
TimSanPham.setLayout(TimSanPhamLayout);
TimSanPhamLayout.setHorizontalGroup(
TimSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(TimSanPhamLayout.createSequentialGroup()
.addContainerGap()
.addGroup(TimSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(TimSanPhamLayout.createSequentialGroup()
.addGroup(TimSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel36)
.addComponent(jLabel38))
.addGap(18, 18, 18)
.addGroup(TimSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cboNhomLoaiSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtTenSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(btnTim, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jScrollPane7, javax.swing.GroupLayout.PREFERRED_SIZE, 526, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
TimSanPhamLayout.setVerticalGroup(
TimSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(TimSanPhamLayout.createSequentialGroup()
.addContainerGap()
.addGroup(TimSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(TimSanPhamLayout.createSequentialGroup()
.addGap(17, 17, 17)
.addGroup(TimSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtTenSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel36))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(TimSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cboNhomLoaiSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel38))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnTim)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jScrollPane7, javax.swing.GroupLayout.DEFAULT_SIZE, 502, Short.MAX_VALUE))
.addContainerGap())
);
tabTimKiem.addTab("Tìm sản phẩm", TimSanPham);
javax.swing.GroupLayout TimKiemLayout = new javax.swing.GroupLayout(TimKiem);
TimKiem.setLayout(TimKiemLayout);
TimKiemLayout.setHorizontalGroup(
TimKiemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(TimKiemLayout.createSequentialGroup()
.addContainerGap()
.addComponent(tabTimKiem)
.addContainerGap())
);
TimKiemLayout.setVerticalGroup(
TimKiemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(TimKiemLayout.createSequentialGroup()
.addContainerGap()
.addComponent(tabTimKiem)
.addContainerGap())
);
QuanLyCuaHang.addTab("Tìm kiếm", null, TimKiem, "");
javax.swing.GroupLayout ThongKeLayout = new javax.swing.GroupLayout(ThongKe);
ThongKe.setLayout(ThongKeLayout);
ThongKeLayout.setHorizontalGroup(
ThongKeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 844, Short.MAX_VALUE)
);
ThongKeLayout.setVerticalGroup(
ThongKeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 574, Short.MAX_VALUE)
);
QuanLyCuaHang.addTab("Thống kê", ThongKe);
javax.swing.GroupLayout KhacHangLayout = new javax.swing.GroupLayout(KhacHang);
KhacHang.setLayout(KhacHangLayout);
KhacHangLayout.setHorizontalGroup(
KhacHangLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 844, Short.MAX_VALUE)
);
KhacHangLayout.setVerticalGroup(
KhacHangLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 574, Short.MAX_VALUE)
);
QuanLyCuaHang.addTab("Khách hàng", KhacHang);
javax.swing.GroupLayout LapPhieuThuLayout = new javax.swing.GroupLayout(LapPhieuThu);
LapPhieuThu.setLayout(LapPhieuThuLayout);
LapPhieuThuLayout.setHorizontalGroup(
LapPhieuThuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 844, Short.MAX_VALUE)
);
LapPhieuThuLayout.setVerticalGroup(
LapPhieuThuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 574, Short.MAX_VALUE)
);
QuanLyCuaHang.addTab("Lập phiếu thu", LapPhieuThu);
javax.swing.GroupLayout KhuyenMaiLayout = new javax.swing.GroupLayout(KhuyenMai);
KhuyenMai.setLayout(KhuyenMaiLayout);
KhuyenMaiLayout.setHorizontalGroup(
KhuyenMaiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 844, Short.MAX_VALUE)
);
KhuyenMaiLayout.setVerticalGroup(
KhuyenMaiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 574, Short.MAX_VALUE)
);
QuanLyCuaHang.addTab("Khuyến mãi", KhuyenMai);
javax.swing.GroupLayout CuaHangLayout = new javax.swing.GroupLayout(CuaHang);
CuaHang.setLayout(CuaHangLayout);
CuaHangLayout.setHorizontalGroup(
CuaHangLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 844, Short.MAX_VALUE)
);
CuaHangLayout.setVerticalGroup(
CuaHangLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 574, Short.MAX_VALUE)
);
QuanLyCuaHang.addTab("Cửa hàng", CuaHang);
javax.swing.GroupLayout SanPhamLayout = new javax.swing.GroupLayout(SanPham);
SanPham.setLayout(SanPhamLayout);
SanPhamLayout.setHorizontalGroup(
SanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 844, Short.MAX_VALUE)
);
SanPhamLayout.setVerticalGroup(
SanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 574, Short.MAX_VALUE)
);
QuanLyCuaHang.addTab("Sản phẩm", SanPham);
javax.swing.GroupLayout NhanVienLayout = new javax.swing.GroupLayout(NhanVien);
NhanVien.setLayout(NhanVienLayout);
NhanVienLayout.setHorizontalGroup(
NhanVienLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 844, Short.MAX_VALUE)
);
NhanVienLayout.setVerticalGroup(
NhanVienLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 574, Short.MAX_VALUE)
);
QuanLyCuaHang.addTab("Nhân viên", NhanVien);
javax.swing.GroupLayout TaiKhoanLayout = new javax.swing.GroupLayout(TaiKhoan);
TaiKhoan.setLayout(TaiKhoanLayout);
TaiKhoanLayout.setHorizontalGroup(
TaiKhoanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 844, Short.MAX_VALUE)
);
TaiKhoanLayout.setVerticalGroup(
TaiKhoanLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 574, Short.MAX_VALUE)
);
QuanLyCuaHang.addTab("Tài khoản", TaiKhoan);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(QuanLyCuaHang, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 849, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(QuanLyCuaHang)
.addContainerGap())
);
QuanLyCuaHang.getAccessibleContext().setAccessibleName("Trang chủ");
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnTimActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTimActionPerformed
/*try {
List resultList = TimSanPhamDAO.getSanPham(txtTenSanPham.getText(), cboNhomLoaiSanPham.getSelectedIndex(), cboNhomLoaiSanPham.getSelectedIndex());
Vector<String> tableHeaders = new Vector<String>();
Vector<Object> tableData = new Vector<Object>();
tableHeaders.add("Tên sản phẩm");
tableHeaders.add("Nhóm sản phẩm");
tableHeaders.add("Giá");
tableHeaders.add("Nhóm sản phẩm");
tableHeaders.add("Mô tả");
for (Object o : resultList) {
Vector oneRow = new Vector();
SanPham sp = (SanPham) o;
oneRow.add(sp.getTenSanPham());
oneRow.add(sp.getNhomLoaiSanPham());
oneRow.add(sp.getDonGia());
oneRow.add(sp.getMoTa());
tableData.add(oneRow);
}
this.tblSanPham.setModel(new DefaultTableModel(tableData, tableHeaders));
} catch (HibernateException he) {
he.printStackTrace();
} */ // TODO add your handling code here:
}//GEN-LAST:event_btnTimActionPerformed
private void btnTim_TimKiem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTim_TimKiem1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btnTim_TimKiem1ActionPerformed
private void btnDanhSachPhieuNhap_PhieuNhapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDanhSachPhieuNhap_PhieuNhapActionPerformed
try {
List resultList = PhieuNhapDAO.getPhieuNhap();
Vector<String> tableHeaders = new Vector<String>();
Vector<Object> tableData = new Vector<Object>();
tableHeaders.add("ID");
tableHeaders.add("Mã phiếu");
tableHeaders.add("Số chứng từ");
tableHeaders.add("Ngày chứng từ");
tableHeaders.add("Ngày nhập hàng");
tableHeaders.add("Ngày tạo");
tableHeaders.add("Loại hóa đơn");
tableHeaders.add("Nhà cung cấp");
tableHeaders.add("Trạng thái");
tableHeaders.add("Nhân viên");
for (Object o : resultList) {
Vector<Object> oneRow = new Vector<Object>();
PhieuNhap pn = (PhieuNhap) o;
oneRow.add(pn.getId());
oneRow.add(pn.getMaPhieu());
oneRow.add(pn.getSoChungTu());
oneRow.add(pn.getNgayChungTu());
oneRow.add(pn.getNgayNhapHang());
oneRow.add(pn.getNgayTao());
oneRow.add(pn.getLoaiHoaDon());
oneRow.add(pn.getNhaCungCap());
oneRow.add(pn.getTrangThai());
oneRow.add(pn.getNhanVien());
tableData.add(oneRow);
}
this.tblPhieuNhap_PhieuNhap.setModel(new DefaultTableModel(tableData, tableHeaders));
} catch (HibernateException he) {
he.printStackTrace();
} // TODO add your handling code here:
}//GEN-LAST:event_btnDanhSachPhieuNhap_PhieuNhapActionPerformed
private void btnHuy_PhieuNhapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHuy_PhieuNhapActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btnHuy_PhieuNhapActionPerformed
private void btnThemPhieuNhap_PhieuNhapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnThemPhieuNhap_PhieuNhapActionPerformed
PhieuNhap pn = new PhieuNhap();
pn.setMaPhieu(txtMaPhieu_PhieuNhap.getText());
pn.setSoChungTu(txtSoChungTu_PhieuNhap.getText());
pn.setDienGiai(txtDienGiai_PhieuNhap.getText());
pn.setNhaCungCap((NhaCungCap) cboNhaCungCap_PhieuNhap.getSelectedItem());
pn.setTrangThai((TrangThai) cboTrangThai_PhieuNhap.getSelectedItem());
pn.setLoaiHoaDon((LoaiHoaDon) cboLoaiHoaDon_PhieuNhap.getSelectedItem());
pn.setNgayNhapHang((Date) spnNgayNhap_PhieuNhap.getModel().getValue());
pn.setNgayChungTu((Date) spnNgayChungTu_PhieuNhap.getModel().getValue());
pn.setNgayTao((Date) spnNgayTao_PhieuNhap.getModel().getValue());
boolean kq;
kq = PhieuNhapDAO.themPhieuNhap(pn);
tblPhieuNhap_PhieuNhap.clearSelection();
loadPhieuNhap();
}//GEN-LAST:event_btnThemPhieuNhap_PhieuNhapActionPerformed
private void btnXoaSanPham_HoaDonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXoaSanPham_HoaDonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btnXoaSanPham_HoaDonActionPerformed
private void btnThemHoaDon_HoaDonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnThemHoaDon_HoaDonActionPerformed
// TODO add your handling code here:
ThemLoaiHoaDon form = new ThemLoaiHoaDon();
form.setVisible(true);
}//GEN-LAST:event_btnThemHoaDon_HoaDonActionPerformed
private void btnDanhSachHoaDon_HoaDonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDanhSachHoaDon_HoaDonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btnDanhSachHoaDon_HoaDonActionPerformed
private void btnHuy_HoaDonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHuy_HoaDonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btnHuy_HoaDonActionPerformed
private void btnTaoHoaDon_HoaDonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTaoHoaDon_HoaDonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btnTaoHoaDon_HoaDonActionPerformed
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
QuanLyCuaHang.setSelectedIndex(6); // TODO add your handling code here:
}//GEN-LAST:event_jButton6ActionPerformed
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
QuanLyCuaHang.setSelectedIndex(7); // TODO add your handling code here:
}//GEN-LAST:event_jButton7ActionPerformed
private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton12ActionPerformed
QuanLyCuaHang.setSelectedIndex(12); // TODO add your handling code here:
}//GEN-LAST:event_jButton12ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
QuanLyCuaHang.setSelectedIndex(2); // TODO add your handling code here:
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton11ActionPerformed
QuanLyCuaHang.setSelectedIndex(11); // TODO add your handling code here:
}//GEN-LAST:event_jButton11ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
QuanLyCuaHang.setSelectedIndex(1); // TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
QuanLyCuaHang.setSelectedIndex(10); // TODO add your handling code here:
}//GEN-LAST:event_jButton10ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
QuanLyCuaHang.setSelectedIndex(3); // TODO add your handling code here:
}//GEN-LAST:event_jButton4ActionPerformed
private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
QuanLyCuaHang.setSelectedIndex(9); // TODO add your handling code here:
}//GEN-LAST:event_jButton9ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
QuanLyCuaHang.setSelectedIndex(4); // TODO add your handling code here:
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
QuanLyCuaHang.setSelectedIndex(8); // TODO add your handling code here:
}//GEN-LAST:event_jButton8ActionPerformed
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
QuanLyCuaHang.setSelectedIndex(5); // TODO add your handling code here:
}//GEN-LAST:event_jButton5ActionPerformed
private void cboNhomLoaiSanPhamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboNhomLoaiSanPhamActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cboNhomLoaiSanPhamActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Pages.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Pages.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Pages.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Pages.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Pages().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel CuaHang;
public javax.swing.JPanel HoaDon;
private javax.swing.JPanel KhacHang;
private javax.swing.JPanel KhuyenMai;
private javax.swing.JPanel LapPhieuThu;
private javax.swing.JPanel NhanVien;
private javax.swing.JPanel PhieuNhap;
private javax.swing.JTabbedPane QuanLyCuaHang;
private javax.swing.JPanel QuyDinh;
private javax.swing.JPanel SanPham;
private javax.swing.JPanel TaiKhoan;
private javax.swing.JPanel ThongKe;
private javax.swing.JPanel TimHoaDon;
private javax.swing.JPanel TimKiem;
private javax.swing.JPanel TimPhieuNhap;
private javax.swing.JPanel TimSanPham;
private javax.swing.JPanel TrangChu;
private javax.swing.JButton btnDanhSachHoaDon_HoaDon;
private javax.swing.JButton btnDanhSachPhieuNhap_PhieuNhap;
private javax.swing.JButton btnHuy_HoaDon;
private javax.swing.JButton btnHuy_PhieuNhap;
private javax.swing.JButton btnTaoHoaDon_HoaDon;
private javax.swing.JButton btnThemHoaDon_HoaDon;
private javax.swing.JButton btnThemLoaiHoaDon_PhieuNhap;
private javax.swing.JButton btnThemNhaCungCap_PhieuNhap;
private javax.swing.JButton btnThemPhieuNhap_PhieuNhap;
private javax.swing.JButton btnThemTrangThai_HoaDon;
private javax.swing.JButton btnThemTrangThai_PhieuNhap;
private javax.swing.JButton btnTim;
private javax.swing.JButton btnTim_TimKiem1;
private javax.swing.JButton btnXoaSanPham_HoaDon;
private javax.swing.JComboBox cboLoaiHoaDon_HoaDon;
private javax.swing.JComboBox cboLoaiHoaDon_PhieuNhap;
private javax.swing.JComboBox cboNhaCungCap_PhieuNhap;
private javax.swing.JComboBox cboNhaSanXuat_HoaDon;
private javax.swing.JComboBox cboNhomLoaiSanPham;
private javax.swing.JComboBox cboNhomLoaiSanPham_TimKiem1;
private javax.swing.JComboBox cboTrangThai_HoaDon;
private javax.swing.JComboBox cboTrangThai_HoaDon1;
private javax.swing.JComboBox cboTrangThai_PhieuNhap;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton10;
private javax.swing.JButton jButton11;
private javax.swing.JButton jButton12;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JButton jButton7;
private javax.swing.JButton jButton8;
private javax.swing.JButton jButton9;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel24;
private javax.swing.JLabel jLabel25;
private javax.swing.JLabel jLabel26;
private javax.swing.JLabel jLabel27;
private javax.swing.JLabel jLabel28;
private javax.swing.JLabel jLabel29;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel30;
private javax.swing.JLabel jLabel31;
private javax.swing.JLabel jLabel32;
private javax.swing.JLabel jLabel33;
private javax.swing.JLabel jLabel34;
private javax.swing.JLabel jLabel35;
private javax.swing.JLabel jLabel36;
private javax.swing.JLabel jLabel37;
private javax.swing.JLabel jLabel38;
private javax.swing.JLabel jLabel39;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JList jList1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollBar jScrollBar1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JScrollPane jScrollPane5;
private javax.swing.JScrollPane jScrollPane6;
private javax.swing.JScrollPane jScrollPane7;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTable jTable2;
private javax.swing.JSpinner spnNgayChungTu_HoaDon;
private javax.swing.JSpinner spnNgayChungTu_PhieuNhap;
private javax.swing.JSpinner spnNgayNhap_PhieuNhap;
private javax.swing.JSpinner spnNgayTao_HoaDon;
private javax.swing.JSpinner spnNgayTao_PhieuNhap;
private javax.swing.JTabbedPane tabTimKiem;
private javax.swing.JTable tblPhieuNhap_PhieuNhap;
private javax.swing.JTable tblSanPham;
private javax.swing.JTextArea txtDienGiai_HoaDon;
private javax.swing.JTextArea txtDienGiai_PhieuNhap;
private javax.swing.JTextField txtKhachHang_HoaDon;
private javax.swing.JTextField txtKhachHang_HoaDon1;
private javax.swing.JTextField txtMaHoaDon_HoaDon;
private javax.swing.JTextField txtMaPhieu_PhieuNhap;
private javax.swing.JTextField txtSoChungTu_HoaDon;
private javax.swing.JTextField txtSoChungTu_PhieuNhap;
private javax.swing.JTextField txtTenSanPham;
private javax.swing.JTextField txtTenSanPham_TimKiem1;
// End of variables declaration//GEN-END:variables
private void loadTenNhom() {
/*try {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String hql = "from NhomLoaiSanPham";
Query q = session.createQuery(hql);
List resultList = q.list();//cai' nay chay xong duoc 1 array list, day gia su lay cai dau tien
NhomLoaiSanPham nhomSP = (NhomLoaiSanPham)resultList.get(0);
String tenNhom = nhomSP.getTenNhomSanPham();
session.getTransaction().commit();
this.txtTenNhom.setText(tenNhom);
} catch (HibernateException he) {
he.printStackTrace();
}*/
}
private void loadNhaCungCap() {
try {
List resultList = NhaCungCapDAO.getNhaCungCap();
this.cboNhaCungCap_PhieuNhap.setModel(new DefaultComboBoxModel(resultList.toArray()));
} catch (HibernateException he) {
he.printStackTrace();
}
}
private void loadTrangThai() {
try {
List resultList = TrangThaiDAO.getTrangThai();
this.cboTrangThai_PhieuNhap.setModel(new DefaultComboBoxModel(resultList.toArray()));
} catch (HibernateException he) {
he.printStackTrace();
}
}
private void loadLoaiHoaDon() {
try {
List resultList = LoaiHoaDonDAO.getLoaiHoaDon();
this.cboLoaiHoaDon_PhieuNhap.setModel(new DefaultComboBoxModel(resultList.toArray()));
} catch (HibernateException he) {
he.printStackTrace();
}
}
private void insertPhieuNhap() {
}
private void loadPhieuNhap() {
}
private void loadNhaSanXuat() {
}
private void loadNhomLoaiSanPham() {
try {
List resultList = NhomLoaiSanPhamDAO.getNhomLoaiSanPham();
this.cboNhomLoaiSanPham.setModel(new DefaultComboBoxModel(resultList.toArray()));
} catch (HibernateException he) {
he.printStackTrace();
}
}
private void loadMenu() {
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package quanlycuahangcongnghe;
import DAO.DonViTinhDAO;
import DAO.NhomLoaiSanPhamDAO;
import DAO.SanPhamDAO;
import DAO.TimSanPhamDAO;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.table.DefaultTableModel;
import org.hibernate.HibernateException;
import qlchcn.entity.DonVi;
import qlchcn.entity.NhomLoaiSanPham;
import qlchcn.entity.SanPham;
import javax.swing.*;
import java.awt.event.*;
/**
*
* @author RUA
*/
public class QuanLySanPham extends javax.swing.JPanel {
/**
* Creates new form SanPham
*/
public QuanLySanPham() {
initComponents();
loadNhomLoaiSanPham();
loadDonViTinh();
enterTxtKeywords();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel6 = new javax.swing.JLabel();
jTextField6 = new javax.swing.JTextField();
tabQuanLySanPham = new javax.swing.JTabbedPane();
pnlThemSanPham = new javax.swing.JPanel();
txtMaSanPham = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
txtTenSanPham = new javax.swing.JTextField();
txtKichThuoc = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
txtKhoiLuong = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
txtDonGia = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
cboDonViTinh = new javax.swing.JComboBox();
jLabel8 = new javax.swing.JLabel();
cboNhomLoaiSanPham = new javax.swing.JComboBox();
jLabel9 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
txtMoTa = new javax.swing.JTextArea();
btnLuu = new javax.swing.JButton();
btnDanhSach = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
tblSanPham = new javax.swing.JTable();
jLabel10 = new javax.swing.JLabel();
txtMauSac = new javax.swing.JTextField();
pnlLoaiSanPham = new javax.swing.JPanel();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
txtMaLoaiSanPham = new javax.swing.JTextField();
txtTenLoaiSanPham = new javax.swing.JTextField();
btnLuuLoaiSanPham = new javax.swing.JButton();
jScrollPane3 = new javax.swing.JScrollPane();
tblNhomLoaiSanPham = new javax.swing.JTable();
pnlXoaSuaSanPham = new javax.swing.JPanel();
btnTim = new javax.swing.JButton();
jScrollPane4 = new javax.swing.JScrollPane();
lisSanPham = new javax.swing.JList();
btnSuaSanPham = new javax.swing.JButton();
btnXoaSanPham = new javax.swing.JButton();
pnlSuaSanPham = new javax.swing.JPanel();
jLabel13 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
txtSuaTenSanPham = new javax.swing.JTextField();
txtSuaKichThuoc = new javax.swing.JTextField();
txtSuaKhoiLuong = new javax.swing.JTextField();
jLabel16 = new javax.swing.JLabel();
jLabel17 = new javax.swing.JLabel();
jLabel18 = new javax.swing.JLabel();
jLabel19 = new javax.swing.JLabel();
jLabel21 = new javax.swing.JLabel();
txtSuaDonGia = new javax.swing.JTextField();
cboSuaDonViTinh = new javax.swing.JComboBox();
cboSuaNhomLoaiSanPham = new javax.swing.JComboBox();
txtSuaMauSac = new javax.swing.JTextField();
jScrollPane5 = new javax.swing.JScrollPane();
txtSuaMoTa = new javax.swing.JTextArea();
btnLuuSuaSanPham = new javax.swing.JButton();
btnHuySuaSanPham = new javax.swing.JButton();
lblId = new javax.swing.JLabel();
lblNotificationLuu = new javax.swing.JLabel();
lblMaSanPham = new javax.swing.JLabel();
txtTuKhoa = new javax.swing.JTextField();
chbInstant = new javax.swing.JCheckBox();
pnlXoaSanPham = new javax.swing.JPanel();
lblNotificationXoa = new javax.swing.JLabel();
btnDongYXoa = new javax.swing.JButton();
btnHuyXoa = new javax.swing.JButton();
jLabel6.setText("Đơn giá:");
jTextField6.setText("jTextField1");
txtMaSanPham.setEditable(false);
jLabel1.setText("Mã sản phẩm:");
jLabel2.setText("Tên sản phẩm:");
jLabel3.setText("Kích thước:");
txtTenSanPham.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtTenSanPhamActionPerformed(evt);
}
});
txtKichThuoc.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtKichThuocActionPerformed(evt);
}
});
jLabel4.setText("Khối lượng:");
jLabel5.setText("Đơn giá:");
jLabel7.setText("Đơn vị tính:");
cboDonViTinh.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel8.setText("Nhóm sản phẩm:");
cboNhomLoaiSanPham.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel9.setText("Mô tả:");
txtMoTa.setColumns(20);
txtMoTa.setRows(5);
jScrollPane1.setViewportView(txtMoTa);
btnLuu.setText("Lưu sản phẩm");
btnLuu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLuuActionPerformed(evt);
}
});
btnDanhSach.setText("Danh sách");
btnDanhSach.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDanhSachActionPerformed(evt);
}
});
tblSanPham.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
tblSanPham.addInputMethodListener(new java.awt.event.InputMethodListener() {
public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
tblSanPhamCaretPositionChanged(evt);
}
public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
tblSanPhamInputMethodTextChanged(evt);
}
});
tblSanPham.addVetoableChangeListener(new java.beans.VetoableChangeListener() {
public void vetoableChange(java.beans.PropertyChangeEvent evt)throws java.beans.PropertyVetoException {
tblSanPhamVetoableChange(evt);
}
});
jScrollPane2.setViewportView(tblSanPham);
jLabel10.setText("Màu sắc:");
javax.swing.GroupLayout pnlThemSanPhamLayout = new javax.swing.GroupLayout(pnlThemSanPham);
pnlThemSanPham.setLayout(pnlThemSanPhamLayout);
pnlThemSanPhamLayout.setHorizontalGroup(
pnlThemSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlThemSanPhamLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlThemSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlThemSanPhamLayout.createSequentialGroup()
.addGroup(pnlThemSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addGroup(pnlThemSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlThemSanPhamLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(txtMaSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(35, 35, 35))
.addGroup(pnlThemSanPhamLayout.createSequentialGroup()
.addGroup(pnlThemSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(txtKhoiLuong, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 152, Short.MAX_VALUE)
.addComponent(txtKichThuoc, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtTenSanPham, javax.swing.GroupLayout.Alignment.LEADING))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(pnlThemSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(pnlThemSanPhamLayout.createSequentialGroup()
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cboDonViTinh, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(pnlThemSanPhamLayout.createSequentialGroup()
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(cboNhomLoaiSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlThemSanPhamLayout.createSequentialGroup()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtDonGia, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(pnlThemSanPhamLayout.createSequentialGroup()
.addComponent(jLabel10)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtMauSac, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(40, 40, 40)
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlThemSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(pnlThemSanPhamLayout.createSequentialGroup()
.addComponent(btnLuu, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnDanhSach, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(110, 110, 110))
.addGroup(pnlThemSanPhamLayout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 884, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
pnlThemSanPhamLayout.setVerticalGroup(
pnlThemSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlThemSanPhamLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlThemSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlThemSanPhamLayout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlThemSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnLuu)
.addComponent(btnDanhSach)))
.addGroup(pnlThemSanPhamLayout.createSequentialGroup()
.addGroup(pnlThemSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtMaSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(jLabel7)
.addComponent(cboDonViTinh, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel9))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlThemSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtTenSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8)
.addComponent(cboNhomLoaiSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlThemSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtKichThuoc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtDonGia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlThemSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlThemSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtMauSac, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10))
.addGroup(pnlThemSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(txtKhoiLuong, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 366, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
tabQuanLySanPham.addTab("Thêm sản phẩm", pnlThemSanPham);
jLabel11.setText("Mã loại sản phẩm: ");
jLabel12.setText("Tên loại sản phẩm:");
btnLuuLoaiSanPham.setText("Lưu");
btnLuuLoaiSanPham.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLuuLoaiSanPhamActionPerformed(evt);
}
});
tblNhomLoaiSanPham.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
tblNhomLoaiSanPham.setCellSelectionEnabled(true);
tblNhomLoaiSanPham.setEnabled(false);
jScrollPane3.setViewportView(tblNhomLoaiSanPham);
javax.swing.GroupLayout pnlLoaiSanPhamLayout = new javax.swing.GroupLayout(pnlLoaiSanPham);
pnlLoaiSanPham.setLayout(pnlLoaiSanPhamLayout);
pnlLoaiSanPhamLayout.setHorizontalGroup(
pnlLoaiSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlLoaiSanPhamLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlLoaiSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3)
.addGroup(pnlLoaiSanPhamLayout.createSequentialGroup()
.addComponent(jLabel11)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtMaLoaiSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel12)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtTenLoaiSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnLuuLoaiSanPham)
.addGap(0, 398, Short.MAX_VALUE)))
.addContainerGap())
);
pnlLoaiSanPhamLayout.setVerticalGroup(
pnlLoaiSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlLoaiSanPhamLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlLoaiSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel11)
.addComponent(jLabel12)
.addComponent(txtMaLoaiSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtTenLoaiSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnLuuLoaiSanPham))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 475, Short.MAX_VALUE)
.addContainerGap())
);
tabQuanLySanPham.addTab("Loại sản phẩm", pnlLoaiSanPham);
btnTim.setText("Tìm");
btnTim.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTimActionPerformed(evt);
}
});
lisSanPham.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
lisSanPham.setToolTipText("");
lisSanPham.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lisSanPhamMouseClicked(evt);
}
});
jScrollPane4.setViewportView(lisSanPham);
btnSuaSanPham.setText("Sửa > ");
btnSuaSanPham.setEnabled(false);
btnSuaSanPham.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSuaSanPhamActionPerformed(evt);
}
});
btnXoaSanPham.setText("Xóa >");
btnXoaSanPham.setEnabled(false);
btnXoaSanPham.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnXoaSanPhamActionPerformed(evt);
}
});
pnlSuaSanPham.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Sửa sản phẩm", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, null, java.awt.Color.darkGray));
pnlSuaSanPham.setEnabled(false);
jLabel13.setText("Tên sản phẩm:");
jLabel14.setText("Kích thước:");
jLabel15.setText("Khối lượng:");
txtSuaTenSanPham.setEnabled(false);
txtSuaKichThuoc.setEnabled(false);
txtSuaKhoiLuong.setEnabled(false);
jLabel16.setText("Đơn vị tính:");
jLabel17.setText("Màu sắc:");
jLabel18.setText("Nhóm sản phẩm:");
jLabel19.setText("Đơn giá:");
jLabel21.setText("Mô tả:");
txtSuaDonGia.setEnabled(false);
cboSuaDonViTinh.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
cboSuaDonViTinh.setEnabled(false);
cboSuaNhomLoaiSanPham.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
cboSuaNhomLoaiSanPham.setEnabled(false);
txtSuaMauSac.setEnabled(false);
txtSuaMoTa.setColumns(20);
txtSuaMoTa.setRows(5);
txtSuaMoTa.setEnabled(false);
jScrollPane5.setViewportView(txtSuaMoTa);
btnLuuSuaSanPham.setText("Lưu");
btnLuuSuaSanPham.setEnabled(false);
btnLuuSuaSanPham.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLuuSuaSanPhamActionPerformed(evt);
}
});
btnHuySuaSanPham.setText("Hủy");
btnHuySuaSanPham.setEnabled(false);
lblId.setFont(new java.awt.Font("Tahoma", 0, 3)); // NOI18N
lblId.setForeground(new java.awt.Color(245, 245, 245));
lblId.setText("-");
lblId.setEnabled(false);
lblMaSanPham.setText("-");
lblMaSanPham.setEnabled(false);
javax.swing.GroupLayout pnlSuaSanPhamLayout = new javax.swing.GroupLayout(pnlSuaSanPham);
pnlSuaSanPham.setLayout(pnlSuaSanPhamLayout);
pnlSuaSanPhamLayout.setHorizontalGroup(
pnlSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlSuaSanPhamLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, pnlSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel19)
.addComponent(jLabel21)
.addComponent(jLabel16)
.addGroup(pnlSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, pnlSuaSanPhamLayout.createSequentialGroup()
.addComponent(jLabel17)
.addGap(48, 48, 48)
.addComponent(txtSuaMauSac))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, pnlSuaSanPhamLayout.createSequentialGroup()
.addComponent(jLabel18)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(cboSuaNhomLoaiSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, pnlSuaSanPhamLayout.createSequentialGroup()
.addGroup(pnlSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel13)
.addComponent(jLabel14)
.addComponent(jLabel15))
.addGroup(pnlSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlSuaSanPhamLayout.createSequentialGroup()
.addGroup(pnlSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlSuaSanPhamLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtSuaKichThuoc, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(pnlSuaSanPhamLayout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(pnlSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtSuaDonGia)
.addComponent(txtSuaKhoiLuong)
.addComponent(txtSuaTenSanPham)
.addComponent(cboSuaDonViTinh, 0, 137, Short.MAX_VALUE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblMaSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblId, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(pnlSuaSanPhamLayout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(pnlSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlSuaSanPhamLayout.createSequentialGroup()
.addComponent(btnLuuSuaSanPham)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnHuySuaSanPham)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblNotificationLuu))
.addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 336, javax.swing.GroupLayout.PREFERRED_SIZE))))))
.addContainerGap(96, Short.MAX_VALUE))
);
pnlSuaSanPhamLayout.setVerticalGroup(
pnlSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlSuaSanPhamLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(pnlSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel13)
.addComponent(txtSuaTenSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblId)
.addComponent(lblMaSanPham))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(pnlSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel14)
.addComponent(txtSuaKichThuoc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(pnlSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel15)
.addComponent(txtSuaKhoiLuong, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(11, 11, 11)
.addGroup(pnlSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel16)
.addComponent(cboSuaDonViTinh, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(pnlSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel17)
.addComponent(txtSuaMauSac, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(pnlSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel18)
.addComponent(cboSuaNhomLoaiSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(pnlSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel19)
.addComponent(txtSuaDonGia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(pnlSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel21)
.addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnHuySuaSanPham)
.addComponent(btnLuuSuaSanPham)
.addComponent(lblNotificationLuu)))
);
chbInstant.setText("Instant");
chbInstant.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chbInstantActionPerformed(evt);
}
});
pnlXoaSanPham.setBorder(javax.swing.BorderFactory.createTitledBorder("Xóa sản phẩm"));
pnlXoaSanPham.setEnabled(false);
lblNotificationXoa.setText("Lưu ý, sản phẩm bị xóa sẽ KHÔNG thể khôi phục lại được, bạn có muốn tiếp tục?");
lblNotificationXoa.setEnabled(false);
btnDongYXoa.setText("Đồng ý");
btnDongYXoa.setEnabled(false);
btnDongYXoa.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDongYXoaActionPerformed(evt);
}
});
btnHuyXoa.setText("Hủy");
btnHuyXoa.setEnabled(false);
btnHuyXoa.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnHuyXoaActionPerformed(evt);
}
});
javax.swing.GroupLayout pnlXoaSanPhamLayout = new javax.swing.GroupLayout(pnlXoaSanPham);
pnlXoaSanPham.setLayout(pnlXoaSanPhamLayout);
pnlXoaSanPhamLayout.setHorizontalGroup(
pnlXoaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlXoaSanPhamLayout.createSequentialGroup()
.addContainerGap()
.addComponent(lblNotificationXoa)
.addGap(8, 8, 8)
.addComponent(btnDongYXoa)
.addGap(3, 3, 3)
.addComponent(btnHuyXoa, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pnlXoaSanPhamLayout.setVerticalGroup(
pnlXoaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlXoaSanPhamLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlXoaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblNotificationXoa)
.addComponent(btnDongYXoa)
.addComponent(btnHuyXoa))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout pnlXoaSuaSanPhamLayout = new javax.swing.GroupLayout(pnlXoaSuaSanPham);
pnlXoaSuaSanPham.setLayout(pnlXoaSuaSanPhamLayout);
pnlXoaSuaSanPhamLayout.setHorizontalGroup(
pnlXoaSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlXoaSuaSanPhamLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlXoaSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlXoaSuaSanPhamLayout.createSequentialGroup()
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlXoaSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnSuaSanPham, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnXoaSanPham, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlXoaSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pnlXoaSanPham, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(pnlSuaSanPham, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(14, 14, 14))
.addGroup(pnlXoaSuaSanPhamLayout.createSequentialGroup()
.addComponent(txtTuKhoa, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(2, 2, 2)
.addComponent(btnTim)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(chbInstant)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
pnlXoaSuaSanPhamLayout.setVerticalGroup(
pnlXoaSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlXoaSuaSanPhamLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlXoaSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnTim)
.addComponent(txtTuKhoa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chbInstant))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlXoaSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(pnlXoaSuaSanPhamLayout.createSequentialGroup()
.addGroup(pnlXoaSuaSanPhamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlXoaSuaSanPhamLayout.createSequentialGroup()
.addComponent(btnSuaSanPham)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnXoaSanPham))
.addComponent(pnlSuaSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(pnlXoaSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane4))
.addContainerGap(31, Short.MAX_VALUE))
);
tabQuanLySanPham.addTab("Xóa/sửa sản phẩm", pnlXoaSuaSanPham);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(tabQuanLySanPham, javax.swing.GroupLayout.PREFERRED_SIZE, 909, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tabQuanLySanPham)
);
}// </editor-fold>//GEN-END:initComponents
private void btnDanhSachActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDanhSachActionPerformed
loadDanhSach();
}//GEN-LAST:event_btnDanhSachActionPerformed
private void btnLuuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLuuActionPerformed
List resultList = SanPhamDAO.getToanBoSanPham();
Integer idLast = 0;
for (Object o : resultList) {
idLast++;
}
SanPham sp = new SanPham();
String txt = Integer.toString(cboNhomLoaiSanPham.getSelectedIndex() + 1) + idLast + txtTenSanPham.getText().substring(0, 3).toUpperCase();
txtMaSanPham.setText(txt);
sp.setMaSanPham(txtMaSanPham.getText());
sp.setTenSanPham(txtTenSanPham.getText());
sp.setKichThuoc(txtKichThuoc.getText());
sp.setKhoiLuong(Float.parseFloat(txtKhoiLuong.getText()));
sp.setDonVi((DonVi) cboDonViTinh.getSelectedItem());
sp.setNhomLoaiSanPham((NhomLoaiSanPham) cboNhomLoaiSanPham.getSelectedItem());
sp.setMoTa(txtMoTa.getText());
sp.setDonGia(Double.parseDouble(txtDonGia.getText()));
sp.setMauSac(txtMauSac.getText());
boolean kq;
kq = SanPhamDAO.themSanPham(sp);
tblSanPham.clearSelection();
loadDanhSach();
}//GEN-LAST:event_btnLuuActionPerformed
private void txtKichThuocActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtKichThuocActionPerformed
}//GEN-LAST:event_txtKichThuocActionPerformed
private void txtTenSanPhamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtTenSanPhamActionPerformed
}//GEN-LAST:event_txtTenSanPhamActionPerformed
private void btnLuuLoaiSanPhamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLuuLoaiSanPhamActionPerformed
NhomLoaiSanPham nlsp = new NhomLoaiSanPham();
nlsp.setMaNhomSanPham(txtMaLoaiSanPham.getText());
nlsp.setTenNhomSanPham(txtTenLoaiSanPham.getText());
boolean kq;
kq = NhomLoaiSanPhamDAO.themNhomLoaiSanPham(nlsp);
tblNhomLoaiSanPham.clearSelection();
loadNhomLoaiSanPham();
}//GEN-LAST:event_btnLuuLoaiSanPhamActionPerformed
private void tblSanPhamInputMethodTextChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_tblSanPhamInputMethodTextChanged
}//GEN-LAST:event_tblSanPhamInputMethodTextChanged
private void tblSanPhamCaretPositionChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_tblSanPhamCaretPositionChanged
// TODO add your handling code here:
}//GEN-LAST:event_tblSanPhamCaretPositionChanged
private void tblSanPhamVetoableChange(java.beans.PropertyChangeEvent evt)throws java.beans.PropertyVetoException {//GEN-FIRST:event_tblSanPhamVetoableChange
// TODO add your handling code here:
}//GEN-LAST:event_tblSanPhamVetoableChange
private void btnTimActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTimActionPerformed
loadThongTinSanPham();
}//GEN-LAST:event_btnTimActionPerformed
private void lisSanPhamMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lisSanPhamMouseClicked
lblNotificationXoa.setEnabled(false);
btnDongYXoa.setEnabled(false);
btnHuyXoa.setEnabled(false);
lblNotificationLuu.setText("");
btnXoaSanPham.setEnabled(true);
btnSuaSanPham.setEnabled(true);
txtSuaDonGia.setEnabled(false);
txtSuaKhoiLuong.setEnabled(false);
txtSuaKichThuoc.setEnabled(false);
txtSuaMauSac.setEnabled(false);
txtSuaMoTa.setEnabled(false);
btnLuuSuaSanPham.setEnabled(false);
btnHuySuaSanPham.setEnabled(false);
txtSuaTenSanPham.setEnabled(false);
cboSuaDonViTinh.setEnabled(false);
cboSuaNhomLoaiSanPham.setEnabled(false);
loadChiTietSanPham();
}//GEN-LAST:event_lisSanPhamMouseClicked
private void btnSuaSanPhamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSuaSanPhamActionPerformed
loadChiTietSanPham();
txtSuaDonGia.setEnabled(true);
txtSuaKhoiLuong.setEnabled(true);
txtSuaKichThuoc.setEnabled(true);
txtSuaMauSac.setEnabled(true);
txtSuaMoTa.setEnabled(true);
txtSuaTenSanPham.setEnabled(true);
cboSuaDonViTinh.setEnabled(true);
cboSuaNhomLoaiSanPham.setEnabled(true);
btnLuuSuaSanPham.setEnabled(true);
btnHuySuaSanPham.setEnabled(true);
}//GEN-LAST:event_btnSuaSanPhamActionPerformed
private void chbInstantActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbInstantActionPerformed
instantTxtKeywords();
}//GEN-LAST:event_chbInstantActionPerformed
private void btnLuuSuaSanPhamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLuuSuaSanPhamActionPerformed
//SanPhamDAO.suaSanPham(Integer.parseInt(lblId.getText()), txtSuaTenSanPham.getText(),txtSuaKichThuoc.getText(),Float.valueOf(txtSuaKhoiLuong.getText().trim()).floatValue(), cboSuaDonViTinh.getSelectedIndex()+1, txtSuaMauSac.getText(), cboSuaNhomLoaiSanPham.getSelectedIndex(), Long.valueOf(txtSuaDonGia.getText().trim()).longValue(), txtSuaMoTa.getText());
SanPham sp = new SanPham();
sp.setId(Integer.parseInt(lblId.getText()));
sp.setTenSanPham(txtSuaTenSanPham.getText());
sp.setKichThuoc(txtSuaKichThuoc.getText());
sp.setKhoiLuong(Float.parseFloat(txtSuaKhoiLuong.getText()));
sp.setDonVi((DonVi) cboSuaDonViTinh.getSelectedItem());
sp.setNhomLoaiSanPham((NhomLoaiSanPham) cboSuaNhomLoaiSanPham.getSelectedItem());
sp.setMoTa(txtSuaMoTa.getText());
sp.setDonGia(Double.parseDouble(txtSuaDonGia.getText()));
sp.setMauSac(txtSuaMauSac.getText());
boolean kq;
kq = SanPhamDAO.suaSanPham(sp);
lisSanPham.clearSelection();
btnTim.doClick();
lblNotificationLuu.setText("Sản phẩm đã được lưu");
}//GEN-LAST:event_btnLuuSuaSanPhamActionPerformed
private void btnXoaSanPhamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXoaSanPhamActionPerformed
lblNotificationXoa.setEnabled(true);
btnDongYXoa.setEnabled(true);
btnHuyXoa.setEnabled(true);
}//GEN-LAST:event_btnXoaSanPhamActionPerformed
private void btnDongYXoaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDongYXoaActionPerformed
SanPham sp = new SanPham();
sp.setId(Integer.parseInt(lblId.getText()));
sp.setTenSanPham(txtSuaTenSanPham.getText());
sp.setKichThuoc(txtSuaKichThuoc.getText());
sp.setKhoiLuong(Float.parseFloat(txtSuaKhoiLuong.getText()));
sp.setDonVi((DonVi) cboSuaDonViTinh.getSelectedItem());
sp.setNhomLoaiSanPham((NhomLoaiSanPham) cboSuaNhomLoaiSanPham.getSelectedItem());
sp.setMoTa(txtSuaMoTa.getText());
sp.setDonGia(Double.parseDouble(txtSuaDonGia.getText()));
sp.setMauSac(txtSuaMauSac.getText());
boolean kq;
kq = SanPhamDAO.xoaSanPham(sp);
lisSanPham.clearSelection();
btnTim.doClick();
}//GEN-LAST:event_btnDongYXoaActionPerformed
private void btnHuyXoaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHuyXoaActionPerformed
btnDongYXoa.setEnabled(false);
btnHuyXoa.setEnabled(false);
}//GEN-LAST:event_btnHuyXoaActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnDanhSach;
private javax.swing.JButton btnDongYXoa;
private javax.swing.JButton btnHuySuaSanPham;
private javax.swing.JButton btnHuyXoa;
private javax.swing.JButton btnLuu;
private javax.swing.JButton btnLuuLoaiSanPham;
private javax.swing.JButton btnLuuSuaSanPham;
private javax.swing.JButton btnSuaSanPham;
private javax.swing.JButton btnTim;
private javax.swing.JButton btnXoaSanPham;
private javax.swing.JComboBox cboDonViTinh;
private javax.swing.JComboBox cboNhomLoaiSanPham;
private javax.swing.JComboBox cboSuaDonViTinh;
private javax.swing.JComboBox cboSuaNhomLoaiSanPham;
private javax.swing.JCheckBox chbInstant;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JScrollPane jScrollPane5;
private javax.swing.JTextField jTextField6;
private javax.swing.JLabel lblId;
private javax.swing.JLabel lblMaSanPham;
private javax.swing.JLabel lblNotificationLuu;
private javax.swing.JLabel lblNotificationXoa;
private javax.swing.JList lisSanPham;
private javax.swing.JPanel pnlLoaiSanPham;
private javax.swing.JPanel pnlSuaSanPham;
private javax.swing.JPanel pnlThemSanPham;
private javax.swing.JPanel pnlXoaSanPham;
private javax.swing.JPanel pnlXoaSuaSanPham;
private javax.swing.JTabbedPane tabQuanLySanPham;
private javax.swing.JTable tblNhomLoaiSanPham;
private javax.swing.JTable tblSanPham;
private javax.swing.JTextField txtDonGia;
private javax.swing.JTextField txtKhoiLuong;
private javax.swing.JTextField txtKichThuoc;
private javax.swing.JTextField txtMaLoaiSanPham;
private javax.swing.JTextField txtMaSanPham;
private javax.swing.JTextField txtMauSac;
private javax.swing.JTextArea txtMoTa;
private javax.swing.JTextField txtSuaDonGia;
private javax.swing.JTextField txtSuaKhoiLuong;
private javax.swing.JTextField txtSuaKichThuoc;
private javax.swing.JTextField txtSuaMauSac;
private javax.swing.JTextArea txtSuaMoTa;
private javax.swing.JTextField txtSuaTenSanPham;
private javax.swing.JTextField txtTenLoaiSanPham;
private javax.swing.JTextField txtTenSanPham;
private javax.swing.JTextField txtTuKhoa;
// End of variables declaration//GEN-END:variables
private void loadNhomLoaiSanPham() {
try {
List resultList = NhomLoaiSanPhamDAO.getNhomLoaiSanPham();
this.cboNhomLoaiSanPham.setModel(new DefaultComboBoxModel(resultList.toArray()));
this.cboSuaNhomLoaiSanPham.setModel(new DefaultComboBoxModel(resultList.toArray()));
} catch (HibernateException he) {
he.printStackTrace();
}
}
private void loadDonViTinh() {
try {
List resultList = DonViTinhDAO.getDonViTinh();
this.cboDonViTinh.setModel(new DefaultComboBoxModel(resultList.toArray()));
this.cboSuaDonViTinh.setModel(new DefaultComboBoxModel(resultList.toArray()));
} catch (HibernateException he) {
he.printStackTrace();
}
}
private void loadDanhSach() {
try {
List resultList = SanPhamDAO.getToanBoSanPham();
Vector<String> tableHeaders = new Vector<String>();
Vector<Object> tableData = new Vector<Object>();
tableHeaders.add("Tên sản phẩm");
tableHeaders.add("Nhóm sản phẩm");
tableHeaders.add("Màu sắc");
tableHeaders.add("Khối lượng");
tableHeaders.add("Kích thước");
tableHeaders.add("Giá");
tableHeaders.add("Mô tả");
for (Object o : resultList) {
Vector oneRow = new Vector();
//Object[] objs = (Object[])o;
//SanPham sp = (SanPham) objs[0];
SanPham sp = (SanPham) o;
oneRow.add(sp.getTenSanPham());
oneRow.add(sp.getNhomLoaiSanPham());
oneRow.add(sp.getMauSac());
oneRow.add(sp.getKhoiLuong());
oneRow.add(sp.getKichThuoc());
DecimalFormat df = new DecimalFormat("#.##");
oneRow.add(df.format(sp.getDonGia()));
oneRow.add(sp.getMoTa());
tableData.add(oneRow);
}
this.tblSanPham.setModel(new DefaultTableModel(tableData, tableHeaders));
} catch (HibernateException he) {
he.printStackTrace();
}
}
private void loadThongTinSanPham() {
try {
List resultList = TimSanPhamDAO.getSanPham(txtTuKhoa.getText());
this.lisSanPham.setModel(new DefaultComboBoxModel(resultList.toArray()));
} catch (HibernateException he) {
he.printStackTrace();
}
}
private void loadChiTietSanPham() {
SanPham a = (SanPham) lisSanPham.getSelectedValue();
txtSuaKhoiLuong.setText(a.getKhoiLuong().toString());
txtSuaTenSanPham.setText(a.getTenSanPham());
txtSuaKichThuoc.setText(a.getKichThuoc());
DecimalFormat df = new DecimalFormat("#.##");
txtSuaDonGia.setText(df.format(a.getDonGia()).toString());
txtSuaMauSac.setText(a.getMauSac());
txtSuaMoTa.setText(a.getMoTa());
lblId.setText(Integer.toString(a.getId()));
lblMaSanPham.setText(a.getMaSanPham());
cboSuaDonViTinh.setSelectedIndex(a.getDonVi().getId() - 1);
cboSuaNhomLoaiSanPham.setSelectedIndex(a.getNhomLoaiSanPham().getId() - 1);
}
private void enterTxtKeywords() {
txtTuKhoa.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
JTextField textField = (JTextField) e.getSource();
String text = textField.getText();
btnTim.doClick();
}
}
});
}
private void instantTxtKeywords() {
//
txtTuKhoa.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
JTextField textField = (JTextField) e.getSource();
String text = textField.getText();
btnTim.doClick();
}
});
}
public class DialogBoxTutorial {
JFrame frame;
public DialogBoxTutorial() {
frame = new JFrame("Simple Dialog Box Demo");
JButton button = new JButton("Show Dialog");
button.addActionListener(new DialogAction());
frame.add(button);
frame.setSize(500, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class DialogAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame,
"This is warning dialog demo.",
"Warning",
JOptionPane.WARNING_MESSAGE);
}
}
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package quanlycuahangcongnghe;
/**
*
* @author RUA
*/
public class KhuyenMai extends javax.swing.JPanel {
/**
* Creates new form KhuyenMai
*/
public KhuyenMai() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel1.setText("km");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jLabel1)
.addContainerGap(891, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jLabel1)
.addContainerGap(473, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package quanlycuahangcongnghe;
/**
*
* @author RUA
*/
public class KhoHang extends javax.swing.JPanel {
/**
* Creates new form KhoHang
*/
public KhoHang() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel1.setText("jLabel1");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jLabel1)
.addContainerGap(871, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jLabel1)
.addContainerGap(472, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package quanlycuahangcongnghe;
import DAO.NhomLoaiSanPhamDAO;
import DAO.TimSanPhamDAO;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import org.hibernate.HibernateException;
import qlchcn.entity.SanPham;
/**
*
* @author RUA
*/
public class TimKiem extends javax.swing.JPanel {
/**
* Creates new form TimKiem
*/
public TimKiem() {
initComponents();
loadNhomLoaiSanPham();
enterTxtKeywords();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jToolBar3 = new javax.swing.JToolBar();
jToolBar4 = new javax.swing.JToolBar();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
txtTuKhoa = new javax.swing.JTextField();
btnTim = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
tblSanPham = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
lbKetQua = new javax.swing.JLabel();
lbTuKhoa = new javax.swing.JLabel();
txtInstant = new javax.swing.JCheckBox();
jToolBar3.setRollover(true);
jToolBar4.setRollover(true);
txtTuKhoa.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtTuKhoaActionPerformed(evt);
}
});
btnTim.setText("Tìm");
btnTim.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTimActionPerformed(evt);
}
});
tblSanPham.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Tên sản phẩm", "Nhóm sản phẩm", "Giá sản phẩm", "Mô tả"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(tblSanPham);
jLabel1.setText("Tên sản phẩm:");
jLabel2.setFont(new java.awt.Font("Tahoma", 2, 10)); // NOI18N
jLabel2.setText("Bạn có thể nhập Tên sản phẩm, Nhóm sản phẩm hoặc Mô tả để tìm kiếm");
jLabel3.setText("Tìm được:");
jLabel4.setText("kết quả với từ khóa");
lbKetQua.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
lbKetQua.setForeground(new java.awt.Color(0, 204, 204));
lbKetQua.setText("-");
lbTuKhoa.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
lbTuKhoa.setForeground(new java.awt.Color(0, 204, 204));
lbTuKhoa.setText("-");
txtInstant.setText("Instant");
txtInstant.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtInstantActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 902, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(400, 400, 400)
.addComponent(jLabel5))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(txtTuKhoa, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnTim)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtInstant))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(142, 142, 142)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lbKetQua, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lbTuKhoa, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtTuKhoa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnTim)
.addComponent(jLabel1)
.addComponent(txtInstant))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(lbKetQua)
.addComponent(jLabel4)
.addComponent(lbTuKhoa))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 396, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel5)
.addGap(23, 23, 23))
);
jTabbedPane1.addTab("Tìm sản phẩm", jPanel1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTabbedPane1)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTabbedPane1)
);
}// </editor-fold>//GEN-END:initComponents
private void btnTimActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTimActionPerformed
try {
List resultList = TimSanPhamDAO.getSanPham(txtTuKhoa.getText());
Vector<String> tableHeaders = new Vector<String>();
Vector<Object> tableData = new Vector<Object>();
tableHeaders.add("Tên sản phẩm");
tableHeaders.add("Nhóm sản phẩm");
tableHeaders.add("Giá");
tableHeaders.add("Mô tả");
for (Object o : resultList) {
Vector oneRow = new Vector();
//Object[] objs = (Object[])o;
//SanPham sp = (SanPham) objs[0];
SanPham sp = (SanPham) o;
oneRow.add(sp.getTenSanPham());
oneRow.add(sp.getNhomLoaiSanPham());
DecimalFormat df = new DecimalFormat("#.##");
oneRow.add(df.format(sp.getDonGia()));
oneRow.add(sp.getMoTa());
tableData.add(oneRow);
}
this.tblSanPham.setModel(new DefaultTableModel(tableData, tableHeaders));
this.lbKetQua.setText(Integer.toString(tblSanPham.getRowCount()));
this.lbTuKhoa.setText(txtTuKhoa.getText());
} catch (HibernateException he) {
he.printStackTrace();
}
}//GEN-LAST:event_btnTimActionPerformed
private void txtTuKhoaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtTuKhoaActionPerformed
}//GEN-LAST:event_txtTuKhoaActionPerformed
private void txtInstantActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtInstantActionPerformed
instantTxtKeywords();
txtInstant.setEnabled(false);
}//GEN-LAST:event_txtInstantActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnTim;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JToolBar jToolBar3;
private javax.swing.JToolBar jToolBar4;
private javax.swing.JLabel lbKetQua;
private javax.swing.JLabel lbTuKhoa;
private javax.swing.JTable tblSanPham;
private javax.swing.JCheckBox txtInstant;
private javax.swing.JTextField txtTuKhoa;
// End of variables declaration//GEN-END:variables
private void loadNhomLoaiSanPham() {
/*List resultList = NhomLoaiSanPhamDAO.getNhomLoaiSanPham();
this.cboNhomLoaiSanPham.setModel(new DefaultComboBoxModel(resultList.toArray()));*/
}
private void instantTxtKeywords() {
//
txtTuKhoa.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
JTextField textField = (JTextField) e.getSource();
String text = textField.getText();
btnTim.doClick();
}
});
}
private void enterTxtKeywords() {
txtTuKhoa.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
JTextField textField = (JTextField) e.getSource();
String text = textField.getText();
btnTim.doClick();
}
}
});
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package quanlycuahangcongnghe;
import DAO.NhanVienDAO;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import org.hibernate.HibernateException;
import qlchcn.entity.NhanVien;
import java.security.*;
/**
*
* @author RUA
*/
public class QuanLyNhanVien extends javax.swing.JPanel {
/**
* Creates new form NhanVien
*/
public QuanLyNhanVien() {
initComponents();
enterTxtKeywords();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
pnlChinhSuaNhanVien = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
txtTuKhoa = new javax.swing.JTextField();
btnTim = new javax.swing.JButton();
chbInstant = new javax.swing.JCheckBox();
jScrollPane4 = new javax.swing.JScrollPane();
lisNhanVien = new javax.swing.JList();
btnSuaNhanVien = new javax.swing.JButton();
btnXoaNhanVien = new javax.swing.JButton();
pnlSuaNhanVien = new javax.swing.JPanel();
txtSuaTenNhanVien = new javax.swing.JTextField();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
txtSuaDiaChi = new javax.swing.JTextField();
txtSuaCMND = new javax.swing.JTextField();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
txtSuaSDT = new javax.swing.JTextField();
jLabel14 = new javax.swing.JLabel();
pswSuaMatKhau = new javax.swing.JPasswordField();
jLabel15 = new javax.swing.JLabel();
spnSuaNgaySinh = new javax.swing.JSpinner();
cboSuaGioiTinh = new javax.swing.JComboBox();
btnLuuSuaNhanVien = new javax.swing.JButton();
btnHuySuaNhanVien = new javax.swing.JButton();
lblID = new javax.swing.JLabel();
lblNotificationLuu = new javax.swing.JLabel();
pnlXoaNhanVien = new javax.swing.JPanel();
s = new javax.swing.JLabel();
lblDongY = new javax.swing.JLabel();
btnDongYXoa = new javax.swing.JButton();
btnHuyXoa = new javax.swing.JButton();
lblXoaNhanVien = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
txtTenNhanVien = new javax.swing.JTextField();
jLabel8 = new javax.swing.JLabel();
txtMaNhanVien = new javax.swing.JTextField();
txtDiaChi = new javax.swing.JTextField();
txtCMND = new javax.swing.JTextField();
txtSoDienThoai = new javax.swing.JTextField();
pswMatKhau = new javax.swing.JPasswordField();
spnNgaySinh = new javax.swing.JSpinner();
cboGioiTinh = new javax.swing.JComboBox();
jScrollPane1 = new javax.swing.JScrollPane();
tblNhanVien = new javax.swing.JTable();
btnThem = new javax.swing.JButton();
btnDanhSach = new javax.swing.JButton();
btnTim.setText("Tìm");
btnTim.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTimActionPerformed(evt);
}
});
chbInstant.setText("Instant");
chbInstant.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
chbInstantActionPerformed(evt);
}
});
lisNhanVien.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
lisNhanVien.setToolTipText("");
lisNhanVien.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lisNhanVienMouseClicked(evt);
}
});
jScrollPane4.setViewportView(lisNhanVien);
btnSuaNhanVien.setText("Sửa > ");
btnSuaNhanVien.setEnabled(false);
btnSuaNhanVien.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSuaNhanVienActionPerformed(evt);
}
});
btnXoaNhanVien.setText("Xóa >");
btnXoaNhanVien.setEnabled(false);
btnXoaNhanVien.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnXoaNhanVienActionPerformed(evt);
}
});
pnlSuaNhanVien.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Sửa nhân viên", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, null, java.awt.Color.gray));
txtSuaTenNhanVien.setEnabled(false);
jLabel9.setText("Tên nhân viên:");
jLabel10.setText("Địa chỉ:");
txtSuaDiaChi.setEnabled(false);
txtSuaCMND.setEnabled(false);
jLabel11.setText("CMND:");
jLabel12.setText("Giới tính:");
jLabel13.setText("SĐT:");
txtSuaSDT.setEnabled(false);
jLabel14.setText("Ngày sinh:");
pswSuaMatKhau.setEnabled(false);
jLabel15.setText("Mật khẩu:");
spnSuaNgaySinh.setModel(new javax.swing.SpinnerDateModel());
spnSuaNgaySinh.setEditor(new javax.swing.JSpinner.DateEditor(spnSuaNgaySinh, "d/M/y"));
spnSuaNgaySinh.setEnabled(false);
cboSuaGioiTinh.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Nam", "Nữ", "Chưa xác định" }));
cboSuaGioiTinh.setEnabled(false);
btnLuuSuaNhanVien.setText("Lưu");
btnLuuSuaNhanVien.setEnabled(false);
btnLuuSuaNhanVien.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLuuSuaNhanVienActionPerformed(evt);
}
});
btnHuySuaNhanVien.setText("Hủy");
btnHuySuaNhanVien.setEnabled(false);
lblID.setText("-");
lblID.setEnabled(false);
javax.swing.GroupLayout pnlSuaNhanVienLayout = new javax.swing.GroupLayout(pnlSuaNhanVien);
pnlSuaNhanVien.setLayout(pnlSuaNhanVienLayout);
pnlSuaNhanVienLayout.setHorizontalGroup(
pnlSuaNhanVienLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlSuaNhanVienLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlSuaNhanVienLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel9)
.addComponent(jLabel10)
.addComponent(jLabel11)
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(pnlSuaNhanVienLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlSuaNhanVienLayout.createSequentialGroup()
.addComponent(btnLuuSuaNhanVien, javax.swing.GroupLayout.DEFAULT_SIZE, 83, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnHuySuaNhanVien))
.addComponent(txtSuaSDT)
.addComponent(txtSuaCMND)
.addComponent(txtSuaDiaChi)
.addComponent(txtSuaTenNhanVien)
.addComponent(pswSuaMatKhau)
.addComponent(spnSuaNgaySinh)
.addComponent(cboSuaGioiTinh, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlSuaNhanVienLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblID)
.addComponent(lblNotificationLuu))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pnlSuaNhanVienLayout.setVerticalGroup(
pnlSuaNhanVienLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlSuaNhanVienLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlSuaNhanVienLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtSuaTenNhanVien, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel9)
.addComponent(lblID))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(pnlSuaNhanVienLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10)
.addComponent(txtSuaDiaChi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(pnlSuaNhanVienLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtSuaCMND, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel11))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(pnlSuaNhanVienLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel12)
.addComponent(cboSuaGioiTinh, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(pnlSuaNhanVienLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel13)
.addComponent(txtSuaSDT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(pnlSuaNhanVienLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel14)
.addComponent(spnSuaNgaySinh, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(pnlSuaNhanVienLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(pswSuaMatKhau, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel15))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(pnlSuaNhanVienLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnLuuSuaNhanVien)
.addComponent(btnHuySuaNhanVien)
.addComponent(lblNotificationLuu))
.addContainerGap(17, Short.MAX_VALUE))
);
pnlXoaNhanVien.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Xóa nhân viên", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, null, java.awt.Color.gray));
s.setText("Chú ý! Xóa nhân viên sẽ ảnh hưởng đến nhiều vấn đề liên quan đến thao tác quản lý. Và KHÔNG thể phục hồi");
lblDongY.setText("Bạn có đồng ý xóa?");
lblDongY.setEnabled(false);
btnDongYXoa.setText("Đồng ý xóa");
btnDongYXoa.setEnabled(false);
btnDongYXoa.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDongYXoaActionPerformed(evt);
}
});
btnHuyXoa.setText("Hủy");
btnHuyXoa.setEnabled(false);
javax.swing.GroupLayout pnlXoaNhanVienLayout = new javax.swing.GroupLayout(pnlXoaNhanVien);
pnlXoaNhanVien.setLayout(pnlXoaNhanVienLayout);
pnlXoaNhanVienLayout.setHorizontalGroup(
pnlXoaNhanVienLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlXoaNhanVienLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlXoaNhanVienLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(s)
.addGroup(pnlXoaNhanVienLayout.createSequentialGroup()
.addComponent(lblDongY)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnDongYXoa)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnHuyXoa)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblXoaNhanVien)))
.addContainerGap(50, Short.MAX_VALUE))
);
pnlXoaNhanVienLayout.setVerticalGroup(
pnlXoaNhanVienLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlXoaNhanVienLayout.createSequentialGroup()
.addContainerGap()
.addComponent(s)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlXoaNhanVienLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblDongY)
.addComponent(btnDongYXoa)
.addComponent(btnHuyXoa)
.addComponent(lblXoaNhanVien))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnSuaNhanVien, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnXoaNhanVien, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pnlXoaNhanVien, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(pnlSuaNhanVien, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(txtTuKhoa, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(2, 2, 2)
.addComponent(btnTim)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(chbInstant)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnTim)
.addComponent(txtTuKhoa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chbInstant))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 444, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(btnSuaNhanVien)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnXoaNhanVien))
.addComponent(pnlSuaNhanVien, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pnlXoaNhanVien, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addContainerGap())
);
pnlChinhSuaNhanVien.addTab("Chỉnh sửa nhân viên", jPanel1);
jLabel1.setText("Tên nhân viên:");
jLabel2.setText("Mã nhân viên:");
jLabel3.setText("Địa chỉ:");
jLabel4.setText("Giới tính:");
jLabel5.setText("Số điện thoại:");
jLabel6.setText("CMND:");
jLabel7.setText("Ngày sinh:");
jLabel8.setText("Mật khẩu:");
txtMaNhanVien.setEditable(false);
spnNgaySinh.setModel(new javax.swing.SpinnerDateModel());
spnNgaySinh.setEditor(new javax.swing.JSpinner.DateEditor(spnNgaySinh, "d/M/y"));
cboGioiTinh.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Nam", "Nữ", "Chưa xác định" }));
tblNhanVien.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(tblNhanVien);
btnThem.setText("Thêm");
btnThem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnThemActionPerformed(evt);
}
});
btnDanhSach.setText("Danh sách");
btnDanhSach.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDanhSachActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane1)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtTenNhanVien, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txtMaNhanVien, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(16, 16, 16)))
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(txtDiaChi)
.addComponent(cboGioiTinh, 0, 151, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(jLabel6))
.addGap(15, 15, 15)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addComponent(btnThem)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnDanhSach))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtSoDienThoai, javax.swing.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE)
.addComponent(txtCMND))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addComponent(jLabel8)
.addGap(10, 10, 10))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel7)
.addGap(7, 7, 7)))
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(spnNgaySinh, javax.swing.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE)
.addComponent(pswMatKhau))))))
.addContainerGap(44, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(spnNgaySinh, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(6, 6, 6)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(pswMatKhau, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(3, 3, 3))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(txtCMND, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(txtSoDienThoai, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtTenNhanVien, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtMaNhanVien, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtDiaChi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(cboGioiTinh, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnDanhSach)
.addComponent(btnThem))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 393, Short.MAX_VALUE)
.addContainerGap())
);
pnlChinhSuaNhanVien.addTab("Thêm nhân viên", jPanel2);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pnlChinhSuaNhanVien)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pnlChinhSuaNhanVien)
);
}// </editor-fold>//GEN-END:initComponents
private void btnThemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnThemActionPerformed
List resultList = NhanVienDAO.getToanBoNhanVien();
Integer idLast = 1;
for (Object o : resultList) {
idLast++;
}
NhanVien nv = new NhanVien();
String txt = Integer.toString(idLast);
txtMaNhanVien.setText(txt);
nv.setHoTen(txtTenNhanVien.getText());
nv.setMaNhanVien(txtMaNhanVien.getText());
nv.setSoCmnd(txtCMND.getText());
nv.setGioiTinh(cboGioiTinh.getSelectedItem().toString());
nv.setDiaChi(txtDiaChi.getText());
nv.setSoDienThoai(txtSoDienThoai.getText());
nv.setNgaySinh((Date) spnNgaySinh.getModel().getValue());
nv.setMatKhau(MD5Covert(pswMatKhau.getPassword().toString()));
boolean kq;
kq = NhanVienDAO.themNhanVien(nv);
tblNhanVien.clearSelection();
loadNhanVien();
}//GEN-LAST:event_btnThemActionPerformed
private void btnDanhSachActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDanhSachActionPerformed
loadNhanVien();
}//GEN-LAST:event_btnDanhSachActionPerformed
private void btnTimActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTimActionPerformed
loadThongTinNhanVien();
}//GEN-LAST:event_btnTimActionPerformed
private void chbInstantActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chbInstantActionPerformed
instantTxtKeywords();
chbInstant.setEnabled(false);
}//GEN-LAST:event_chbInstantActionPerformed
private void lisNhanVienMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lisNhanVienMouseClicked
btnSuaNhanVien.setEnabled(true);
txtSuaCMND.setEnabled(false);
txtSuaSDT.setEnabled(false);
txtSuaDiaChi.setEnabled(false);
cboSuaGioiTinh.setEnabled(false);
pswSuaMatKhau.setEnabled(false);
spnSuaNgaySinh.setEnabled(false);
txtSuaTenNhanVien.setEnabled(false);
btnLuuSuaNhanVien.setEnabled(false);
btnHuySuaNhanVien.setEnabled(false);
lblDongY.setEnabled(false);
btnDongYXoa.setEnabled(false);
btnHuyXoa.setEnabled(false);
lblXoaNhanVien.setText(" ");
lblNotificationLuu.setText(" ");
btnXoaNhanVien.setEnabled(true);
loadChiTietNhanVien();
}//GEN-LAST:event_lisNhanVienMouseClicked
private void btnSuaNhanVienActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSuaNhanVienActionPerformed
txtSuaCMND.setEnabled(true);
txtSuaSDT.setEnabled(true);
txtSuaDiaChi.setEnabled(true);
cboSuaGioiTinh.setEnabled(true);
pswSuaMatKhau.setEnabled(true);
spnSuaNgaySinh.setEnabled(true);
txtSuaTenNhanVien.setEnabled(true);
btnLuuSuaNhanVien.setEnabled(true);
btnHuySuaNhanVien.setEnabled(true);
}//GEN-LAST:event_btnSuaNhanVienActionPerformed
private void btnXoaNhanVienActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXoaNhanVienActionPerformed
lblDongY.setEnabled(true);
btnDongYXoa.setEnabled(true);
btnHuyXoa.setEnabled(true);
}//GEN-LAST:event_btnXoaNhanVienActionPerformed
private void btnLuuSuaNhanVienActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLuuSuaNhanVienActionPerformed
NhanVien nv = new NhanVien();
nv.setDiaChi(txtSuaDiaChi.getText());
nv.setGioiTinh(cboSuaGioiTinh.getSelectedItem().toString());
nv.setNgaySinh((Date) spnSuaNgaySinh.getModel().getValue());
nv.setHoTen(txtSuaTenNhanVien.getText());
nv.setId(Integer.parseInt(lblID.getText()));
nv.setMatKhau(MD5Covert(pswSuaMatKhau.getPassword().toString()));
nv.setSoDienThoai(txtSuaSDT.getText());
nv.setSoCmnd(txtSuaCMND.getText());
nv.setMaNhanVien(lblID.getText());
boolean kq;
kq = NhanVienDAO.suaNhanVien(nv);
lisNhanVien.clearSelection();
btnTim.doClick();
lblNotificationLuu.setText("Nhân viên đã được lưu");
}//GEN-LAST:event_btnLuuSuaNhanVienActionPerformed
private void btnDongYXoaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDongYXoaActionPerformed
NhanVien nv = new NhanVien();
nv.setId(Integer.parseInt(lblID.getText()));
boolean kq;
kq = NhanVienDAO.xoaNhanVien(nv);
lisNhanVien.clearSelection();
btnTim.doClick();
lblXoaNhanVien.setText("Bạn đã vừa cho ra đi một nhân viên");
}//GEN-LAST:event_btnDongYXoaActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnDanhSach;
private javax.swing.JButton btnDongYXoa;
private javax.swing.JButton btnHuySuaNhanVien;
private javax.swing.JButton btnHuyXoa;
private javax.swing.JButton btnLuuSuaNhanVien;
private javax.swing.JButton btnSuaNhanVien;
private javax.swing.JButton btnThem;
private javax.swing.JButton btnTim;
private javax.swing.JButton btnXoaNhanVien;
private javax.swing.JComboBox cboGioiTinh;
private javax.swing.JComboBox cboSuaGioiTinh;
private javax.swing.JCheckBox chbInstant;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JLabel lblDongY;
private javax.swing.JLabel lblID;
private javax.swing.JLabel lblNotificationLuu;
private javax.swing.JLabel lblXoaNhanVien;
private javax.swing.JList lisNhanVien;
private javax.swing.JTabbedPane pnlChinhSuaNhanVien;
private javax.swing.JPanel pnlSuaNhanVien;
private javax.swing.JPanel pnlXoaNhanVien;
private javax.swing.JPasswordField pswMatKhau;
private javax.swing.JPasswordField pswSuaMatKhau;
private javax.swing.JLabel s;
private javax.swing.JSpinner spnNgaySinh;
private javax.swing.JSpinner spnSuaNgaySinh;
private javax.swing.JTable tblNhanVien;
private javax.swing.JTextField txtCMND;
private javax.swing.JTextField txtDiaChi;
private javax.swing.JTextField txtMaNhanVien;
private javax.swing.JTextField txtSoDienThoai;
private javax.swing.JTextField txtSuaCMND;
private javax.swing.JTextField txtSuaDiaChi;
private javax.swing.JTextField txtSuaSDT;
private javax.swing.JTextField txtSuaTenNhanVien;
private javax.swing.JTextField txtTenNhanVien;
private javax.swing.JTextField txtTuKhoa;
// End of variables declaration//GEN-END:variables
private void loadNhanVien() {
try {
List resultList = NhanVienDAO.getToanBoNhanVien();
Vector<String> tableHeaders = new Vector<String>();
Vector<Object> tableData = new Vector<Object>();
tableHeaders.add("Mã đăng nhập");
tableHeaders.add("Tên nhân viên");
tableHeaders.add("Địa chỉ");
tableHeaders.add("SĐT");
tableHeaders.add("CMND");
tableHeaders.add("Giới tính");
tableHeaders.add("Ngày sinh");
for (Object o : resultList) {
Vector oneRow = new Vector();
NhanVien nv = (NhanVien) o;
oneRow.add(nv.getMaNhanVien());
oneRow.add(nv.getHoTen());
oneRow.add(nv.getDiaChi());
oneRow.add(nv.getSoDienThoai());
oneRow.add(nv.getSoCmnd());
oneRow.add(nv.getGioiTinh());
oneRow.add(nv.getNgaySinh());
tableData.add(oneRow);
}
this.tblNhanVien.setModel(new DefaultTableModel(tableData, tableHeaders));
} catch (HibernateException he) {
he.printStackTrace();
}
}
private void enterTxtKeywords() {
txtTuKhoa.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
JTextField textField = (JTextField) e.getSource();
String text = textField.getText();
btnTim.doClick();
}
}
});
}
private void loadThongTinNhanVien() {
try {
List resultList = NhanVienDAO.getNhanVien(txtTuKhoa.getText());
lisNhanVien.setModel(new DefaultComboBoxModel(resultList.toArray()));
} catch (HibernateException he) {
he.printStackTrace();
}
}
private void instantTxtKeywords() {
//
txtTuKhoa.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
JTextField textField = (JTextField) e.getSource();
String text = textField.getText();
btnTim.doClick();
}
});
}
private void loadChiTietNhanVien() {
NhanVien nv = (NhanVien) lisNhanVien.getSelectedValue();
txtSuaTenNhanVien.setText(nv.getHoTen());
txtSuaDiaChi.setText(nv.getDiaChi());
txtSuaSDT.setText(nv.getSoDienThoai());
cboSuaGioiTinh.setSelectedItem(nv.getGioiTinh());
spnSuaNgaySinh.setValue((Date) nv.getNgaySinh());
txtSuaCMND.setText(nv.getSoCmnd());
lblID.setText(Integer.toString(nv.getId()));
}
private static String MD5Covert(String md5) {
String res = "";
try {
MessageDigest algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(md5.getBytes());
byte[] MD5Covert = algorithm.digest();
String tmp = "";
for (int i = 0; i < MD5Covert.length; i++) {
tmp = (Integer.toHexString(0xFF & MD5Covert[i]));
if (tmp.length() == 1) {
res += "0" + tmp;
} else {
res += tmp;
}
}
} catch (NoSuchAlgorithmException ex) {
}
return res;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package quanlycuahangcongnghe;
/**
*
* @author RUA
*/
public class KhachHang extends javax.swing.JPanel {
/**
* Creates new form KhachHang
*/
public KhachHang() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel1.setText("jLabel1");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(jLabel1)
.addContainerGap(871, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jLabel1)
.addContainerGap(473, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package qlchcn.util;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
/**
* Hibernate Utility class with a convenient method to get Session Factory
* object.
*
* @author RUA
*/
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import qlchcn.entity.NhaCungCap;
import qlchcn.util.HibernateUtil;
/**
*
* @author RUA
*/
public class NhaCungCapDAO {
public static List getNhaCungCap() {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String hql = "from NhaCungCap";
Query q = session.createQuery(hql);
List resultList = q.list();
session.getTransaction().commit();
return resultList;
} catch (HibernateException he) {
he.printStackTrace();
}
return null;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.transform.DistinctRootEntityResultTransformer;
import org.hibernate.transform.ResultTransformer;
import qlchcn.entity.SanPham;
import qlchcn.util.HibernateUtil;
/**
*
* @author RUA
*/
public class SanPhamDAO {
public static List getToanBoSanPham() {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String hql = "from SanPham";
Query q = session.createQuery(hql);
List resultList = q.list();
session.getTransaction().commit();
return resultList;
} catch (HibernateException he) {
he.printStackTrace();
}
return null;
}
public static List getSanPham(String keyWords) {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String hql = "select distinct sp from SanPham sp, NhomLoaiSanPham nlsp where upper(sp.moTa) like :keyWords or upper(sp.tenSanPham) like :keyWords or upper(nlsp.tenNhomSanPham) like :keyWords group by sp.id";
Query q = session.createQuery(hql);
//q.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);// select distinct
q.setString("keyWords", "%" + keyWords.toUpperCase() + "%");
//q.setInteger("nhomSanPham", nhomSanPham);
//q.setInteger("nhomSanPham", giaSanPham);
final ResultTransformer trans = new DistinctRootEntityResultTransformer();
q.setResultTransformer(trans);
List resultList = q.list();
session.getTransaction().commit();
return resultList;
} catch (HibernateException he) {
he.printStackTrace();
}
return null;
}
public static boolean themSanPham(SanPham sanPham) {
Session session = HibernateUtil.getSessionFactory().openSession();
boolean kq = true;
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.save(sanPham);
transaction.commit();
} catch (HibernateException ex) {
transaction.rollback();
System.err.println(ex);
kq = false;
} finally {
session.close();
}
return kq;
}
public static boolean suaSanPham(SanPham sanPham) {
Session session = HibernateUtil.getSessionFactory().openSession();
boolean kq = true;
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.update(sanPham);
transaction.commit();
} catch (HibernateException ex) {
transaction.rollback();
System.err.println(ex);
kq = false;
} finally {
session.close();
}
return kq;
}
public static boolean xoaSanPham(SanPham sanPham) {
Session session = HibernateUtil.getSessionFactory().openSession();
boolean kq = true;
Transaction transaction = null;
transaction = session.beginTransaction();
try {
session.delete(sanPham);
transaction.commit();
} catch (Exception e) {
transaction.rollback();
System.err.println(e);
kq = false;
}
session.close();
return kq;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import java.sql.Date;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import qlchcn.entity.PhieuNhap;
import qlchcn.util.HibernateUtil;
/**
*
* @author RUA
*/
public class PhieuNhapDAO {
public static List getPhieuNhap() {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String hql = "from PhieuNhap";
Query q = session.createQuery(hql);
List resultList = q.list();
session.getTransaction().commit();
return resultList;
} catch (HibernateException he) {
he.printStackTrace();
}
return null;
}
public static boolean themPhieuNhap(PhieuNhap phieunhap) {
Session session = HibernateUtil.getSessionFactory().openSession();
boolean kq = true;
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.save(phieunhap);
transaction.commit();
} catch (HibernateException ex) {
transaction.rollback();
System.err.println(ex);
kq = false;
} finally {
session.close();
}
return kq;
}
} | Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import qlchcn.util.HibernateUtil;
/**
*
* @author RUA
*/
public class DonViTinhDAO {
public static List getDonViTinh() {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String hql = "from DonVi";
Query q = session.createQuery(hql);
List resultList = q.list();
session.getTransaction().commit();
return resultList;
} catch (HibernateException he) {
he.printStackTrace();
}
return null;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import qlchcn.entity.TrangThai;
import qlchcn.util.HibernateUtil;
/**
*
* @author RUA
*/
public class TrangThaiDAO {
public static List getTrangThai() {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String hql = "from TrangThai";
Query q = session.createQuery(hql);
List resultList = q.list();
session.getTransaction().commit();
return resultList;
} catch (HibernateException he) {
he.printStackTrace();
}
return null;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.transform.DistinctRootEntityResultTransformer;
import org.hibernate.transform.ResultTransformer;
import qlchcn.entity.NhanVien;
import qlchcn.util.HibernateUtil;
/**
*
* @author RUA
*/
public class NhanVienDAO {
public static boolean themNhanVien(NhanVien nhanVien) {
Session session = HibernateUtil.getSessionFactory().openSession();
boolean kq = true;
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.save(nhanVien);
transaction.commit();
} catch (HibernateException ex) {
transaction.rollback();
System.err.println(ex);
kq = false;
} finally {
session.close();
}
return kq;
}
public static List getToanBoNhanVien() {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String hql = "from NhanVien";
Query q = session.createQuery(hql);
List resultList = q.list();
session.getTransaction().commit();
return resultList;
} catch (HibernateException he) {
he.printStackTrace();
}
return null;
}
public static List getNhanVien(String keyWords) {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String hql = "select distinct nv from NhanVien nv where upper(nv.hoTen) like :keyWords";
Query q = session.createQuery(hql);
q.setParameter("keyWords", "%" + keyWords.toUpperCase() + "%");
final ResultTransformer trans = new DistinctRootEntityResultTransformer();
q.setResultTransformer(trans);
List resultList = q.list();
session.getTransaction().commit();
return resultList;
} catch (HibernateException he) {
he.printStackTrace();
}
return null;
}
public static boolean suaNhanVien(NhanVien nhanVien) {
Session session = HibernateUtil.getSessionFactory().openSession();
boolean kq = true;
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.update(nhanVien);
transaction.commit();
} catch (HibernateException ex) {
transaction.rollback();
System.err.println(ex);
kq = false;
} finally {
session.close();
}
return kq;
}
public static boolean xoaNhanVien(NhanVien nhanVien) {
Session session = HibernateUtil.getSessionFactory().openSession();
boolean kq = true;
Transaction transaction = null;
transaction = session.beginTransaction();
try {
session.delete(nhanVien);
transaction.commit();
} catch (Exception e) {
transaction.rollback();
System.err.println(e);
kq = false;
}
session.close();
return kq;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import qlchcn.entity.LoaiHoaDon;
import qlchcn.util.HibernateUtil;
/**
*
* @author RUA
*/
public class LoaiHoaDonDAO {
public static List getLoaiHoaDon() {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String hql = "from LoaiHoaDon";
Query q = session.createQuery(hql);
List resultList = q.list();
session.getTransaction().commit();
return resultList;
} catch (HibernateException he) {
he.printStackTrace();
}
return null;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import qlchcn.entity.NhomLoaiSanPham;
import qlchcn.util.HibernateUtil;
/**
*
* @author RUA
*/
public class NhomLoaiSanPhamDAO {
public static List getNhomLoaiSanPham() {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String hql = "from NhomLoaiSanPham";
Query q = session.createQuery(hql);
List resultList = q.list();
session.getTransaction().commit();
return resultList;
} catch (HibernateException he) {
he.printStackTrace();
}
return null;
}
public static boolean themNhomLoaiSanPham(NhomLoaiSanPham nlsp) {
Session session = HibernateUtil.getSessionFactory().openSession();
boolean kq = true;
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.save(nlsp);
transaction.commit();
} catch (HibernateException ex) {
transaction.rollback();
System.err.println(ex);
kq = false;
} finally {
session.close();
}
return kq;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.transform.DistinctRootEntityResultTransformer;
import org.hibernate.transform.ResultTransformer;
import qlchcn.entity.SanPham;
import qlchcn.entity.NhomLoaiSanPham;
import qlchcn.util.HibernateUtil;
/**
*
* @author RUA
*/
public class TimSanPhamDAO {
public static List getSanPham(String keyWords) {
try {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String hql = "select distinct sp from SanPham sp, NhomLoaiSanPham nlsp where upper(sp.moTa) like :keyWords or upper(sp.tenSanPham) like :keyWords or upper(nlsp.tenNhomSanPham) like :keyWords group by sp.id";
Query q = session.createQuery(hql);
//q.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);// select distinct
q.setString("keyWords", "%" + keyWords.toUpperCase() + "%");
//q.setInteger("nhomSanPham", nhomSanPham);
//q.setInteger("nhomSanPham", giaSanPham);
final ResultTransformer trans = new DistinctRootEntityResultTransformer();
q.setResultTransformer(trans);
List resultList = q.list();
session.getTransaction().commit();
return resultList;
} catch (HibernateException he) {
he.printStackTrace();
}
return null;
}
}
| Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.util.Log;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.http.HttpClient;
import com.ch_linghu.fanfoudroid.ui.module.MyTextView;
public class PreferencesActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//禁止横屏
if (TwitterApplication.mPref.getBoolean(
Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
// TODO: is this a hack?
setResult(RESULT_OK);
addPreferencesFromResource(R.xml.preferences);
}
@Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
Preference preference) {
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if ( key.equalsIgnoreCase(Preferences.NETWORK_TYPE) ) {
HttpClient httpClient = TwitterApplication.mApi.getHttpClient();
String type = sharedPreferences.getString(Preferences.NETWORK_TYPE, "");
if (type.equalsIgnoreCase(getString(R.string.pref_network_type_cmwap))) {
Log.d("LDS", "Set proxy for cmwap mode.");
httpClient.setProxy("10.0.0.172", 80, "http");
} else {
Log.d("LDS", "No proxy.");
httpClient.removeProxy();
}
} else if ( key.equalsIgnoreCase(Preferences.UI_FONT_SIZE)) {
MyTextView.setFontSizeChanged(true);
}
}
}
| Java |
package com.ch_linghu.fanfoudroid.app;
import java.util.HashMap;
import android.graphics.Bitmap;
public class MemoryImageCache implements ImageCache {
private HashMap<String, Bitmap> mCache;
public MemoryImageCache() {
mCache = new HashMap<String, Bitmap>();
}
@Override
public Bitmap get(String url) {
synchronized(this) {
Bitmap bitmap = mCache.get(url);
if (bitmap == null){
return mDefaultBitmap;
}else{
return bitmap;
}
}
}
@Override
public void put(String url, Bitmap bitmap) {
synchronized(this) {
mCache.put(url, bitmap);
}
}
public void putAll(MemoryImageCache imageCache) {
synchronized(this) {
// TODO: is this thread safe?
mCache.putAll(imageCache.mCache);
}
}
}
| Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid.app;
public class Preferences {
public static final String USERNAME_KEY = "username";
public static final String PASSWORD_KEY = "password";
public static final String CHECK_UPDATES_KEY = "check_updates";
public static final String CHECK_UPDATE_INTERVAL_KEY = "check_update_interval";
public static final String VIBRATE_KEY = "vibrate";
public static final String TIMELINE_ONLY_KEY = "timeline_only";
public static final String REPLIES_ONLY_KEY = "replies_only";
public static final String DM_ONLY_KEY = "dm_only";
public static String RINGTONE_KEY = "ringtone";
public static final String RINGTONE_DEFAULT_KEY = "content://settings/system/notification_sound";
public static final String LAST_TWEET_REFRESH_KEY = "last_tweet_refresh";
public static final String LAST_DM_REFRESH_KEY = "last_dm_refresh";
public static final String LAST_FOLLOWERS_REFRESH_KEY = "last_followers_refresh";
public static final String TWITTER_ACTIVITY_STATE_KEY = "twitter_activity_state";
public static final String USE_PROFILE_IMAGE = "use_profile_image";
public static final String PHOTO_PREVIEW = "photo_preview";
public static final String FORCE_SHOW_ALL_IMAGE = "force_show_all_image";
public static final String RT_PREFIX_KEY = "rt_prefix";
public static final String RT_INSERT_APPEND = "rt_insert_append"; // 转发时光标放置在开始还是结尾
public static final String NETWORK_TYPE = "network_type";
// DEBUG标记
public static final String DEBUG = "debug";
// 当前用户相关信息
public static final String CURRENT_USER_ID = "current_user_id";
public static final String CURRENT_USER_SCREEN_NAME = "current_user_screenname";
public static final String UI_FONT_SIZE = "ui_font_size";
public static final String USE_ENTER_SEND = "use_enter_send";
public static final String USE_GESTRUE = "use_gestrue";
public static final String USE_SHAKE = "use_shake";
public static final String FORCE_SCREEN_ORIENTATION_PORTRAIT = "force_screen_orientation_portrait";
}
| Java |
package com.ch_linghu.fanfoudroid.app;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.text.method.MovementMethod;
import android.view.MotionEvent;
import android.widget.TextView;
public class TestMovementMethod extends LinkMovementMethod {
private double mY;
private boolean mIsMoving = false;
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer,
MotionEvent event) {
/*
int action = event.getAction();
if (action == MotionEvent.ACTION_MOVE) {
double deltaY = mY - event.getY();
mY = event.getY();
Log.d("foo", deltaY + "");
if (Math.abs(deltaY) > 1) {
mIsMoving = true;
}
} else if (action == MotionEvent.ACTION_DOWN) {
mIsMoving = false;
mY = event.getY();
} else if (action == MotionEvent.ACTION_UP) {
boolean wasMoving = mIsMoving;
mIsMoving = false;
if (wasMoving) {
return true;
}
}
*/
return super.onTouchEvent(widget, buffer, event);
}
public static MovementMethod getInstance() {
if (sInstance == null)
sInstance = new TestMovementMethod();
return sInstance;
}
private static TestMovementMethod sInstance;
} | Java |
package com.ch_linghu.fanfoudroid.app;
import android.app.Activity;
import android.content.Intent;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.LoginActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.fanfou.RefuseError;
import com.ch_linghu.fanfoudroid.http.HttpAuthException;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.HttpRefusedException;
import com.ch_linghu.fanfoudroid.http.HttpServerException;
public class ExceptionHandler {
private Activity mActivity;
public ExceptionHandler(Activity activity) {
mActivity = activity;
}
public void handle(HttpException e) {
Throwable cause = e.getCause();
if (null == cause) return;
// Handle Different Exception
if (cause instanceof HttpAuthException) {
// 用户名/密码错误
Toast.makeText(mActivity, R.string.error_not_authorized, Toast.LENGTH_LONG).show();
Intent intent = new Intent(mActivity, LoginActivity.class);
mActivity.startActivity(intent); // redirect to the login activity
} else if (cause instanceof HttpServerException) {
// 服务器暂时无法响应
Toast.makeText(mActivity, R.string.error_not_authorized, Toast.LENGTH_LONG).show();
} else if (cause instanceof HttpAuthException) {
//FIXME: 集中处理用户名/密码验证错误,返回到登录界面
} else if (cause instanceof HttpRefusedException) {
// 服务器拒绝请求,如没有权限查看某用户信息
RefuseError error = ((HttpRefusedException) cause).getError();
switch (error.getErrorCode()) {
// TODO: finish it
case -1:
default:
Toast.makeText(mActivity, error.getMessage(), Toast.LENGTH_LONG).show();
break;
}
}
}
private void handleCause() {
}
}
| Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid.app;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* Manages retrieval and storage of icon images. Use the put method to download
* and store images. Use the get method to retrieve images from the manager.
*/
public class ImageManager implements ImageCache {
private static final String TAG = "ImageManager";
// 饭否目前最大宽度支持596px, 超过则同比缩小
// 最大高度为1192px, 超过从中截取
public static final int DEFAULT_COMPRESS_QUALITY = 90;
public static final int IMAGE_MAX_WIDTH = 596;
public static final int IMAGE_MAX_HEIGHT = 1192;
private Context mContext;
// In memory cache.
private Map<String, SoftReference<Bitmap>> mCache;
// MD5 hasher.
private MessageDigest mDigest;
public static Bitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap = Bitmap
.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable
.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
public ImageManager(Context context) {
mContext = context;
mCache = new HashMap<String, SoftReference<Bitmap>>();
try {
mDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
// This shouldn't happen.
throw new RuntimeException("No MD5 algorithm.");
}
}
public void setContext(Context context) {
mContext = context;
}
private String getHashString(MessageDigest digest) {
StringBuilder builder = new StringBuilder();
for (byte b : digest.digest()) {
builder.append(Integer.toHexString((b >> 4) & 0xf));
builder.append(Integer.toHexString(b & 0xf));
}
return builder.toString();
}
// MD5 hases are used to generate filenames based off a URL.
private String getMd5(String url) {
mDigest.update(url.getBytes());
return getHashString(mDigest);
}
// Looks to see if an image is in the file system.
private Bitmap lookupFile(String url) {
String hashedUrl = getMd5(url);
FileInputStream fis = null;
try {
fis = mContext.openFileInput(hashedUrl);
return BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
// Not there.
return null;
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// Ignore.
}
}
}
}
/**
* Downloads a file
* @param url
* @return
* @throws HttpException
*/
public Bitmap downloadImage(String url) throws HttpException {
Log.d(TAG, "Fetching image: " + url);
Response res = TwitterApplication.mApi.getHttpClient().get(url);
return BitmapFactory.decodeStream(new BufferedInputStream(res.asStream()));
}
public Bitmap downloadImage2(String url) throws HttpException {
Log.d(TAG, "[NEW]Fetching image: " + url);
final Response res = TwitterApplication.mApi.getHttpClient().get(url);
String file = writeToFile(res.asStream(), getMd5(url));
return BitmapFactory.decodeFile(file);
}
/**
* 下载远程图片 -> 转换为Bitmap -> 写入缓存器.
* @param url
* @param quality image quality 1~100
* @throws HttpException
*/
public void put(String url, int quality, boolean forceOverride) throws HttpException {
if (!forceOverride && contains(url)) {
// Image already exists.
return;
// TODO: write to file if not present.
}
Bitmap bitmap = downloadImage(url);
if (bitmap != null) {
put(url, bitmap, quality); // file cache
} else {
Log.w(TAG, "Retrieved bitmap is null.");
}
}
/**
* 重载 put(String url, int quality)
* @param url
* @throws HttpException
*/
public void put(String url) throws HttpException {
put(url, DEFAULT_COMPRESS_QUALITY, false);
}
/**
* 将本地File -> 转换为Bitmap -> 写入缓存器.
* 如果图片大小超过MAX_WIDTH/MAX_HEIGHT, 则将会对图片缩放.
*
* @param file
* @param quality 图片质量(0~100)
* @param forceOverride
* @throws IOException
*/
public void put(File file, int quality, boolean forceOverride) throws IOException {
if (!file.exists()) {
Log.w(TAG, file.getName() + " is not exists.");
return;
}
if (!forceOverride && contains(file.getPath())) {
// Image already exists.
Log.d(TAG, file.getName() + " is exists");
return;
// TODO: write to file if not present.
}
Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
//bitmap = resizeBitmap(bitmap, MAX_WIDTH, MAX_HEIGHT);
if (bitmap == null) {
Log.w(TAG, "Retrieved bitmap is null.");
} else {
put(file.getPath(), bitmap, quality);
}
}
/**
* 将Bitmap写入缓存器.
* @param filePath file path
* @param bitmap
* @param quality 1~100
*/
public void put(String file, Bitmap bitmap, int quality) {
synchronized (this) {
mCache.put(file, new SoftReference<Bitmap>(bitmap));
}
writeFile(file, bitmap, quality);
}
/**
* 重载 put(String file, Bitmap bitmap, int quality)
* @param filePath file path
* @param bitmap
* @param quality 1~100
*/
@Override
public void put(String file, Bitmap bitmap) {
put(file, bitmap, DEFAULT_COMPRESS_QUALITY);
}
/**
* 将Bitmap写入本地缓存文件.
* @param file URL/PATH
* @param bitmap
* @param quality
*/
private void writeFile(String file, Bitmap bitmap, int quality) {
if (bitmap == null) {
Log.w(TAG, "Can't write file. Bitmap is null.");
return;
}
BufferedOutputStream bos = null;
try {
String hashedUrl = getMd5(file);
bos = new BufferedOutputStream(
mContext.openFileOutput(hashedUrl, Context.MODE_PRIVATE));
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos); // PNG
Log.d(TAG, "Writing file: " + file);
} catch (IOException ioe) {
Log.e(TAG, ioe.getMessage());
} finally {
try {
if (bos != null) {
bitmap.recycle();
bos.flush();
bos.close();
}
//bitmap.recycle();
} catch (IOException e) {
Log.e(TAG, "Could not close file.");
}
}
}
private String writeToFile(InputStream is, String filename) {
Log.d("LDS", "new write to file");
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(is);
out = new BufferedOutputStream(
mContext.openFileOutput(filename, Context.MODE_PRIVATE));
byte[] buffer = new byte[1024];
int l;
while ((l = in.read(buffer)) != -1) {
out.write(buffer, 0, l);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (in != null) in.close();
if (out != null) {
Log.d("LDS", "new write to file to -> " + filename);
out.flush();
out.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return mContext.getFilesDir() + "/" + filename;
}
public Bitmap get(File file) {
return get(file.getPath());
}
/**
* 判断缓存着中是否存在该文件对应的bitmap
*/
public boolean isContains(String file) {
return mCache.containsKey(file);
}
/**
* 获得指定file/URL对应的Bitmap,首先找本地文件,如果有直接使用,否则去网上获取
* @param file file URL/file PATH
* @param bitmap
* @param quality
* @throws HttpException
*/
public Bitmap safeGet(String file) throws HttpException {
Bitmap bitmap = lookupFile(file); // first try file.
if (bitmap != null) {
synchronized (this) { // memory cache
mCache.put(file, new SoftReference<Bitmap>(bitmap));
}
return bitmap;
} else { //get from web
String url = file;
bitmap = downloadImage2(url);
// 注释掉以测试新的写入文件方法
//put(file, bitmap); // file Cache
return bitmap;
}
}
/**
* 从缓存器中读取文件
* @param file file URL/file PATH
* @param bitmap
* @param quality
*/
public Bitmap get(String file) {
SoftReference<Bitmap> ref;
Bitmap bitmap;
// Look in memory first.
synchronized (this) {
ref = mCache.get(file);
}
if (ref != null) {
bitmap = ref.get();
if (bitmap != null) {
return bitmap;
}
}
// Now try file.
bitmap = lookupFile(file);
if (bitmap != null) {
synchronized (this) {
mCache.put(file, new SoftReference<Bitmap>(bitmap));
}
return bitmap;
}
//TODO: why?
//upload: see profileImageCacheManager line 96
Log.w(TAG, "Image is missing: " + file);
// return the default photo
return mDefaultBitmap;
}
public boolean contains(String url) {
return get(url) != mDefaultBitmap;
}
public void clear() {
String[] files = mContext.fileList();
for (String file : files) {
mContext.deleteFile(file);
}
synchronized (this) {
mCache.clear();
}
}
public void cleanup(HashSet<String> keepers) {
String[] files = mContext.fileList();
HashSet<String> hashedUrls = new HashSet<String>();
for (String imageUrl : keepers) {
hashedUrls.add(getMd5(imageUrl));
}
for (String file : files) {
if (!hashedUrls.contains(file)) {
Log.d(TAG, "Deleting unused file: " + file);
mContext.deleteFile(file);
}
}
}
/**
* Compress and resize the Image
*
* <br />
* 因为不论图片大小和尺寸如何, 饭否都会对图片进行一次有损压缩, 所以本地压缩应该
* 考虑图片将会被二次压缩所造成的图片质量损耗
*
* @param targetFile
* @param quality, 0~100, recommend 100
* @return
* @throws IOException
*/
public File compressImage(File targetFile, int quality) throws IOException {
String filepath = targetFile.getAbsolutePath();
// 1. Calculate scale
int scale = 1;
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filepath, o);
if (o.outWidth > IMAGE_MAX_WIDTH || o.outHeight > IMAGE_MAX_HEIGHT) {
scale = (int) Math.pow( 2.0,
(int) Math.round(Math.log(IMAGE_MAX_WIDTH
/ (double) Math.max(o.outHeight, o.outWidth))
/ Math.log(0.5)));
//scale = 2;
}
Log.d(TAG, scale + " scale");
// 2. File -> Bitmap (Returning a smaller image)
o.inJustDecodeBounds = false;
o.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFile(filepath, o);
// 2.1. Resize Bitmap
//bitmap = resizeBitmap(bitmap, IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT);
// 3. Bitmap -> File
writeFile(filepath, bitmap, quality);
// 4. Get resized Image File
String filePath = getMd5(targetFile.getPath());
File compressedImage = mContext.getFileStreamPath(filePath);
return compressedImage;
}
/**
* 保持长宽比缩小Bitmap
*
* @param bitmap
* @param maxWidth
* @param maxHeight
* @param quality 1~100
* @return
*/
public Bitmap resizeBitmap(Bitmap bitmap, int maxWidth, int maxHeight) {
int originWidth = bitmap.getWidth();
int originHeight = bitmap.getHeight();
// no need to resize
if (originWidth < maxWidth && originHeight < maxHeight) {
return bitmap;
}
int newWidth = originWidth;
int newHeight = originHeight;
// 若图片过宽, 则保持长宽比缩放图片
if (originWidth > maxWidth) {
newWidth = maxWidth;
double i = originWidth * 1.0 / maxWidth;
newHeight = (int) Math.floor(originHeight / i);
bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
}
// 若图片过长, 则从中部截取
if (newHeight > maxHeight) {
newHeight = maxHeight;
int half_diff = (int)((originHeight - maxHeight) / 2.0);
bitmap = Bitmap.createBitmap(bitmap, 0, half_diff, newWidth, newHeight);
}
Log.d(TAG, newWidth + " width");
Log.d(TAG, newHeight + " height");
return bitmap;
}
}
| Java |
package com.ch_linghu.fanfoudroid.app;
import android.graphics.Bitmap;
import android.widget.ImageView;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
public class SimpleImageLoader {
public static void display(final ImageView imageView, String url) {
imageView.setTag(url);
imageView.setImageBitmap(TwitterApplication.mImageLoader
.get(url, createImageViewCallback(imageView, url)));
}
public static ImageLoaderCallback createImageViewCallback(final ImageView imageView, String url)
{
return new ImageLoaderCallback() {
@Override
public void refresh(String url, Bitmap bitmap) {
if (url.equals(imageView.getTag())) {
imageView.setImageBitmap(bitmap);
}
}
};
}
}
| Java |
package com.ch_linghu.fanfoudroid.app;
import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.http.HttpException;
public class LazyImageLoader {
private static final String TAG = "ProfileImageCacheManager";
public static final int HANDLER_MESSAGE_ID = 1;
public static final String EXTRA_BITMAP = "extra_bitmap";
public static final String EXTRA_IMAGE_URL = "extra_image_url";
private ImageManager mImageManager = new ImageManager(
TwitterApplication.mContext);
private BlockingQueue<String> mUrlList = new ArrayBlockingQueue<String>(50);
private CallbackManager mCallbackManager = new CallbackManager();
private GetImageTask mTask = new GetImageTask();
/**
* 取图片, 可能直接从cache中返回, 或下载图片后返回
*
* @param url
* @param callback
* @return
*/
public Bitmap get(String url, ImageLoaderCallback callback) {
Bitmap bitmap = ImageCache.mDefaultBitmap;
if (mImageManager.isContains(url)) {
bitmap = mImageManager.get(url);
} else {
// bitmap不存在,启动Task进行下载
mCallbackManager.put(url, callback);
startDownloadThread(url);
}
return bitmap;
}
private void startDownloadThread(String url) {
if (url != null) {
addUrlToDownloadQueue(url);
}
// Start Thread
State state = mTask.getState();
if (Thread.State.NEW == state) {
mTask.start(); // first start
} else if (Thread.State.TERMINATED == state) {
mTask = new GetImageTask(); // restart
mTask.start();
}
}
private void addUrlToDownloadQueue(String url) {
if (!mUrlList.contains(url)) {
try {
mUrlList.put(url);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// Low-level interface to get ImageManager
public ImageManager getImageManager() {
return mImageManager;
}
private class GetImageTask extends Thread {
private volatile boolean mTaskTerminated = false;
private static final int TIMEOUT = 3 * 60;
private boolean isPermanent = true;
@Override
public void run() {
try {
while (!mTaskTerminated) {
String url;
if (isPermanent) {
url = mUrlList.take();
} else {
url = mUrlList.poll(TIMEOUT, TimeUnit.SECONDS); // waiting
if (null == url) {
break;
} // no more, shutdown
}
// Bitmap bitmap = ImageCache.mDefaultBitmap;
final Bitmap bitmap = mImageManager.safeGet(url);
// use handler to process callback
final Message m = handler.obtainMessage(HANDLER_MESSAGE_ID);
Bundle bundle = m.getData();
bundle.putString(EXTRA_IMAGE_URL, url);
bundle.putParcelable(EXTRA_BITMAP, bitmap);
handler.sendMessage(m);
}
} catch (HttpException ioe) {
Log.e(TAG, "Get Image failed, " + ioe.getMessage());
} catch (InterruptedException e) {
Log.w(TAG, e.getMessage());
} finally {
Log.v(TAG, "Get image task terminated.");
mTaskTerminated = true;
}
}
@SuppressWarnings("unused")
public boolean isPermanent() {
return isPermanent;
}
@SuppressWarnings("unused")
public void setPermanent(boolean isPermanent) {
this.isPermanent = isPermanent;
}
@SuppressWarnings("unused")
public void shutDown() throws InterruptedException {
mTaskTerminated = true;
}
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case HANDLER_MESSAGE_ID:
final Bundle bundle = msg.getData();
String url = bundle.getString(EXTRA_IMAGE_URL);
Bitmap bitmap = (Bitmap) (bundle.get(EXTRA_BITMAP));
// callback
mCallbackManager.call(url, bitmap);
break;
default:
// do nothing.
}
}
};
public interface ImageLoaderCallback {
void refresh(String url, Bitmap bitmap);
}
public static class CallbackManager {
private static final String TAG = "CallbackManager";
private ConcurrentHashMap<String, List<ImageLoaderCallback>> mCallbackMap;
public CallbackManager() {
mCallbackMap = new ConcurrentHashMap<String, List<ImageLoaderCallback>>();
}
public void put(String url, ImageLoaderCallback callback) {
Log.v(TAG, "url=" + url);
if (!mCallbackMap.containsKey(url)) {
Log.v(TAG, "url does not exist, add list to map");
mCallbackMap.put(url, new ArrayList<ImageLoaderCallback>());
//mCallbackMap.put(url, Collections.synchronizedList(new ArrayList<ImageLoaderCallback>()));
}
mCallbackMap.get(url).add(callback);
Log.v(TAG, "Add callback to list, count(url)=" + mCallbackMap.get(url).size());
}
public void call(String url, Bitmap bitmap) {
Log.v(TAG, "call url=" + url);
List<ImageLoaderCallback> callbackList = mCallbackMap.get(url);
if (callbackList == null) {
// FIXME: 有时会到达这里,原因我还没想明白
Log.e(TAG, "callbackList=null");
return;
}
for (ImageLoaderCallback callback : callbackList) {
if (callback != null) {
callback.refresh(url, bitmap);
}
}
callbackList.clear();
mCallbackMap.remove(url);
}
}
}
| Java |
package com.ch_linghu.fanfoudroid.app;
import android.graphics.Bitmap;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
public interface ImageCache {
public static Bitmap mDefaultBitmap = ImageManager.drawableToBitmap(TwitterApplication.mContext.getResources().getDrawable(R.drawable.user_default_photo));
public Bitmap get(String url);
public void put(String url, Bitmap bitmap);
}
| Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid.data;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class Tweet extends Message implements Parcelable {
private static final String TAG = "Tweet";
public com.ch_linghu.fanfoudroid.fanfou.User user;
public String source;
public String prevId;
private int statusType = -1; // @see StatusTable#TYPE_*
public void setStatusType(int type) {
statusType = type;
}
public int getStatusType() {
return statusType;
}
public Tweet(){}
public static Tweet create(Status status){
Tweet tweet = new Tweet();
tweet.id = status.getId();
//转义符放到getSimpleTweetText里去处理,这里不做处理
tweet.text = status.getText();
tweet.createdAt = status.getCreatedAt();
tweet.favorited = status.isFavorited()?"true":"false";
tweet.truncated = status.isTruncated()?"true":"false";
tweet.inReplyToStatusId = status.getInReplyToStatusId();
tweet.inReplyToUserId = status.getInReplyToUserId();
tweet.inReplyToScreenName = status.getInReplyToScreenName();
tweet.screenName = TextHelper.getSimpleTweetText(status.getUser().getScreenName());
tweet.profileImageUrl = status.getUser().getProfileImageURL().toString();
tweet.userId = status.getUser().getId();
tweet.user = status.getUser();
tweet.thumbnail_pic = status.getThumbnail_pic();
tweet.bmiddle_pic = status.getBmiddle_pic();
tweet.original_pic = status.getOriginal_pic();
tweet.source = TextHelper.getSimpleTweetText(status.getSource());
return tweet;
}
public static Tweet createFromSearchApi(JSONObject jsonObject) throws JSONException {
Tweet tweet = new Tweet();
tweet.id = jsonObject.getString("id") + "";
//转义符放到getSimpleTweetText里去处理,这里不做处理
tweet.text = jsonObject.getString("text");
tweet.createdAt = DateTimeHelper.parseSearchApiDateTime(jsonObject.getString("created_at"));
tweet.favorited = jsonObject.getString("favorited");
tweet.truncated = jsonObject.getString("truncated");
tweet.inReplyToStatusId = jsonObject.getString("in_reply_to_status_id");
tweet.inReplyToUserId = jsonObject.getString("in_reply_to_user_id");
tweet.inReplyToScreenName = jsonObject.getString("in_reply_to_screen_name");
tweet.screenName = TextHelper.getSimpleTweetText(jsonObject.getString("from_user"));
tweet.profileImageUrl = jsonObject.getString("profile_image_url");
tweet.userId = jsonObject.getString("from_user_id");
tweet.source = TextHelper.getSimpleTweetText(jsonObject.getString("source"));
return tweet;
}
public static String buildMetaText(StringBuilder builder,
Date createdAt, String source, String replyTo) {
builder.setLength(0);
builder.append(DateTimeHelper.getRelativeDate(createdAt));
builder.append(" ");
builder.append(TwitterApplication.mContext.getString(R.string.tweet_source_prefix));
builder.append(source);
if (!TextUtils.isEmpty(replyTo)) {
builder.append(" " + TwitterApplication.mContext.getString(R.string.tweet_reply_to_prefix));
builder.append(replyTo);
builder.append(TwitterApplication.mContext.getString(R.string.tweet_reply_to_suffix));
}
return builder.toString();
}
// For interface Parcelable
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(id);
out.writeString(text);
out.writeValue(createdAt); //Date
out.writeString(screenName);
out.writeString(favorited);
out.writeString(inReplyToStatusId);
out.writeString(inReplyToUserId);
out.writeString(inReplyToScreenName);
out.writeString(screenName);
out.writeString(profileImageUrl);
out.writeString(thumbnail_pic);
out.writeString(bmiddle_pic);
out.writeString(original_pic);
out.writeString(userId);
out.writeString(source);
}
public static final Parcelable.Creator<Tweet> CREATOR
= new Parcelable.Creator<Tweet>() {
public Tweet createFromParcel(Parcel in) {
return new Tweet(in);
}
public Tweet[] newArray(int size) {
// return new Tweet[size];
throw new UnsupportedOperationException();
}
};
public Tweet(Parcel in) {
id = in.readString();
text = in.readString();
createdAt = (Date) in.readValue(Date.class.getClassLoader());
screenName = in.readString();
favorited = in.readString();
inReplyToStatusId = in.readString();
inReplyToUserId = in.readString();
inReplyToScreenName = in.readString();
screenName = in.readString();
profileImageUrl = in.readString();
thumbnail_pic = in.readString();
bmiddle_pic = in.readString();
original_pic = in.readString();
userId = in.readString();
source = in.readString();
}
@Override
public String toString() {
return "Tweet [source=" + source + ", id=" + id + ", screenName="
+ screenName + ", text=" + text + ", profileImageUrl="
+ profileImageUrl + ", createdAt=" + createdAt + ", userId="
+ userId + ", favorited=" + favorited + ", inReplyToStatusId="
+ inReplyToStatusId + ", inReplyToUserId=" + inReplyToUserId
+ ", inReplyToScreenName=" + inReplyToScreenName + "]";
}
}
| Java |
package com.ch_linghu.fanfoudroid.data;
import android.database.Cursor;
public interface BaseContent {
long insert();
int delete();
int update();
Cursor select();
}
| Java |
package com.ch_linghu.fanfoudroid.data;
import com.ch_linghu.fanfoudroid.fanfou.DirectMessage;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class Dm extends Message {
@SuppressWarnings("unused")
private static final String TAG = "Dm";
public boolean isSent;
public static Dm create(DirectMessage directMessage, boolean isSent){
Dm dm = new Dm();
dm.id = directMessage.getId();
dm.text = directMessage.getText();
dm.createdAt = directMessage.getCreatedAt();
dm.isSent = isSent;
User user = dm.isSent ? directMessage.getRecipient()
: directMessage.getSender();
dm.screenName = TextHelper.getSimpleTweetText(user.getScreenName());
dm.userId = user.getId();
dm.profileImageUrl = user.getProfileImageURL().toString();
return dm;
}
} | Java |
package com.ch_linghu.fanfoudroid.data;
import java.util.Date;
import android.os.Parcel;
import android.os.Parcelable;
public class User implements Parcelable {
public String id;
public String name;
public String screenName;
public String location;
public String description;
public String profileImageUrl;
public String url;
public boolean isProtected;
public int followersCount;
public String lastStatus;
public int friendsCount;
public int favoritesCount;
public int statusesCount;
public Date createdAt;
public boolean isFollowing;
// public boolean notifications;
// public utc_offset
public User() {}
public static User create(com.ch_linghu.fanfoudroid.fanfou.User u) {
User user = new User();
user.id = u.getId();
user.name = u.getName();
user.screenName = u.getScreenName();
user.location = u.getLocation();
user.description = u.getDescription();
user.profileImageUrl = u.getProfileImageURL().toString();
if (u.getURL() != null) {
user.url = u.getURL().toString();
}
user.isProtected = u.isProtected();
user.followersCount = u.getFollowersCount();
user.lastStatus = u.getStatusText();
user.friendsCount = u.getFriendsCount();
user.favoritesCount = u.getFavouritesCount();
user.statusesCount = u.getStatusesCount();
user.createdAt = u.getCreatedAt();
user.isFollowing = u.isFollowing();
return user;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
boolean[] boolArray = new boolean[] { isProtected, isFollowing };
out.writeString(id);
out.writeString(name);
out.writeString(screenName);
out.writeString(location);
out.writeString(description);
out.writeString(profileImageUrl);
out.writeString(url);
out.writeBooleanArray(boolArray);
out.writeInt(friendsCount);
out.writeInt(followersCount);
out.writeInt(statusesCount);
}
public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() {
public User createFromParcel(Parcel in) {
return new User(in);
}
public User[] newArray(int size) {
// return new User[size];
throw new UnsupportedOperationException();
}
};
public User(Parcel in){
boolean[] boolArray = new boolean[]{isProtected, isFollowing};
id = in.readString();
name = in.readString();
screenName = in.readString();
location = in.readString();
description = in.readString();
profileImageUrl = in.readString();
url = in.readString();
in.readBooleanArray(boolArray);
friendsCount = in.readInt();
followersCount = in.readInt();
statusesCount = in.readInt();
isProtected = boolArray[0];
isFollowing = boolArray[1];
}
}
| Java |
package com.ch_linghu.fanfoudroid.data;
import java.util.Date;
public class Message {
public String id;
public String screenName;
public String text;
public String profileImageUrl;
public Date createdAt;
public String userId;
public String favorited;
public String truncated;
public String inReplyToStatusId;
public String inReplyToUserId;
public String inReplyToScreenName;
public String thumbnail_pic;
public String bmiddle_pic;
public String original_pic;
}
| Java |
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.hardware.SensorManager;
import android.util.Log;
import android.widget.RemoteViews;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.service.TwitterService;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class FanfouWidget extends AppWidgetProvider {
public final String TAG = "FanfouWidget";
public final String NEXTACTION = "com.ch_linghu.fanfoudroid.FanfouWidget.NEXT";
public final String PREACTION = "com.ch_linghu.fanfoudroid.FanfouWidget.PREV";
private static List<Tweet> tweets;
private SensorManager sensorManager;
private static int position = 0;
class CacheCallback implements ImageLoaderCallback {
private RemoteViews updateViews;
CacheCallback(RemoteViews updateViews) {
this.updateViews = updateViews;
}
@Override
public void refresh(String url, Bitmap bitmap) {
updateViews.setImageViewBitmap(R.id.status_image, bitmap);
}
}
@Override
public void onUpdate(Context context, AppWidgetManager appwidgetmanager,
int[] appWidgetIds) {
Log.d(TAG, "onUpdate");
TwitterService.setWidgetStatus(true);
// if (!isRunning(context, WidgetService.class.getName())) {
// Intent i = new Intent(context, WidgetService.class);
// context.startService(i);
// }
update(context);
}
private void update(Context context) {
fetchMessages();
position = 0;
refreshView(context, NEXTACTION);
}
private TwitterDatabase getDb() {
return TwitterApplication.mDb;
}
public String getUserId() {
return TwitterApplication.getMyselfId();
}
private void fetchMessages() {
if (tweets == null) {
tweets = new ArrayList<Tweet>();
} else {
tweets.clear();
}
Cursor cursor = getDb().fetchAllTweets(getUserId(),
StatusTable.TYPE_HOME);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Tweet tweet = StatusTable.parseCursor(cursor);
tweets.add(tweet);
} while (cursor.moveToNext());
}
}
Log.d(TAG, "Tweets size " + tweets.size());
}
private void refreshView(Context context) {
ComponentName fanfouWidget = new ComponentName(context,
FanfouWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(fanfouWidget, buildLogin(context));
}
private RemoteViews buildLogin(Context context) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_initial_layout);
updateViews.setTextViewText(R.id.status_text,
TextHelper.getSimpleTweetText("请登录"));
updateViews.setTextViewText(R.id.status_screen_name,"");
updateViews.setTextViewText(R.id.tweet_source,"");
updateViews.setTextViewText(R.id.tweet_created_at,
"");
return updateViews;
}
private void refreshView(Context context, String action) {
// 某些情况下,tweets会为null
if (tweets == null) {
fetchMessages();
}
// 防止引发IndexOutOfBoundsException
if (tweets.size() != 0) {
if (action.equals(NEXTACTION)) {
--position;
} else if (action.equals(PREACTION)) {
++position;
}
// Log.d(TAG, "Tweets size =" + tweets.size());
if (position >= tweets.size() || position < 0) {
position = 0;
}
// Log.d(TAG, "position=" + position);
ComponentName fanfouWidget = new ComponentName(context,
FanfouWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(fanfouWidget, buildUpdate(context));
}
}
public RemoteViews buildUpdate(Context context) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_initial_layout);
Tweet t = tweets.get(position);
Log.d(TAG, "tweet=" + t);
updateViews.setTextViewText(R.id.status_screen_name, t.screenName);
updateViews.setTextViewText(R.id.status_text,
TextHelper.getSimpleTweetText(t.text));
updateViews.setTextViewText(R.id.tweet_source,
context.getString(R.string.tweet_source_prefix) + t.source);
updateViews.setTextViewText(R.id.tweet_created_at,
DateTimeHelper.getRelativeDate(t.createdAt));
updateViews.setImageViewBitmap(R.id.status_image,
TwitterApplication.mImageLoader.get(
t.profileImageUrl, new CacheCallback(updateViews)));
Intent inext = new Intent(context, FanfouWidget.class);
inext.setAction(NEXTACTION);
PendingIntent pinext = PendingIntent.getBroadcast(context, 0, inext,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.btn_next, pinext);
Intent ipre = new Intent(context, FanfouWidget.class);
ipre.setAction(PREACTION);
PendingIntent pipre = PendingIntent.getBroadcast(context, 0, ipre,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.btn_pre, pipre);
Intent write = WriteActivity.createNewTweetIntent("");
PendingIntent piwrite = PendingIntent.getActivity(context, 0, write,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.write_message, piwrite);
Intent home = TwitterActivity.createIntent(context);
PendingIntent pihome = PendingIntent.getActivity(context, 0, home,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.logo_image, pihome);
Intent status = StatusActivity.createIntent(t);
PendingIntent pistatus = PendingIntent.getActivity(context, 0, status,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.main_body, pistatus);
return updateViews;
}
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "OnReceive");
// FIXME: NullPointerException
Log.i(TAG, context.getApplicationContext().toString());
if (!TwitterApplication.mApi.isLoggedIn()) {
refreshView(context);
} else {
super.onReceive(context, intent);
String action = intent.getAction();
if (NEXTACTION.equals(action) || PREACTION.equals(action)) {
refreshView(context, intent.getAction());
} else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
update(context);
}
}
}
/**
*
* @param c
* @param serviceName
* @return
*/
@Deprecated
public boolean isRunning(Context c, String serviceName) {
ActivityManager myAM = (ActivityManager) c
.getSystemService(Context.ACTIVITY_SERVICE);
ArrayList<RunningServiceInfo> runningServices = (ArrayList<RunningServiceInfo>) myAM
.getRunningServices(40);
// 获取最多40个当前正在运行的服务,放进ArrList里,以现在手机的处理能力,要是超过40个服务,估计已经卡死,所以不用考虑超过40个该怎么办
int servicesSize = runningServices.size();
for (int i = 0; i < servicesSize; i++)// 循环枚举对比
{
if (runningServices.get(i).service.getClassName().toString()
.equals(serviceName)) {
return true;
}
}
return false;
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
Log.d(TAG, "onDeleted");
}
@Override
public void onEnabled(Context context) {
Log.d(TAG, "onEnabled");
TwitterService.setWidgetStatus(true);
}
@Override
public void onDisabled(Context context) {
Log.d(TAG, "onDisabled");
TwitterService.setWidgetStatus(false);
}
}
| Java |
package com.ch_linghu.fanfoudroid;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Dm;
import com.ch_linghu.fanfoudroid.db.MessageTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.DirectMessage;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.base.Refreshable;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class DmActivity extends BaseActivity implements Refreshable {
private static final String TAG = "DmActivity";
// Views.
private ListView mTweetList;
private Adapter mAdapter;
private Adapter mInboxAdapter;
private Adapter mSendboxAdapter;
Button inbox;
Button sendbox;
Button newMsg;
private int mDMType;
private static final int DM_TYPE_ALL = 0;
private static final int DM_TYPE_INBOX = 1;
private static final int DM_TYPE_SENDBOX = 2;
private TextView mProgressText;
private NavBar mNavbar;
private Feedback mFeedback;
// Tasks.
private GenericTask mRetrieveTask;
private GenericTask mDeleteTask;
private TaskListener mDeleteTaskListener = new TaskAdapter(){
@Override
public void onPreExecute(GenericTask task) {
updateProgress(getString(R.string.page_status_deleting));
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
mAdapter.refresh();
} else {
// Do nothing.
}
updateProgress("");
}
@Override
public String getName() {
return "DmDeleteTask";
}
};
private TaskListener mRetrieveTaskListener = new TaskAdapter(){
@Override
public void onPreExecute(GenericTask task) {
updateProgress(getString(R.string.page_status_refreshing));
}
@Override
public void onProgressUpdate(GenericTask task, Object params) {
draw();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
SharedPreferences.Editor editor = mPreferences.edit();
editor.putLong(Preferences.LAST_DM_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
draw();
goTop();
} else {
// Do nothing.
}
updateProgress("");
}
@Override
public String getName() {
return "DmRetrieve";
}
};
// Refresh data at startup if last refresh was this long ago or greater.
private static final long REFRESH_THRESHOLD = 5 * 60 * 1000;
private static final String EXTRA_USER = "user";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.DMS";
public static Intent createIntent() {
return createIntent("");
}
public static Intent createIntent(String user) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (!TextUtils.isEmpty(user)) {
intent.putExtra(EXTRA_USER, user);
}
return intent;
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState))
{
setContentView(R.layout.dm);
mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this);
mNavbar.setHeaderTitle("我的私信");
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
bindFooterButtonEvent();
mTweetList = (ListView) findViewById(R.id.tweet_list);
mProgressText = (TextView) findViewById(R.id.progress_text);
TwitterDatabase db = getDb();
// Mark all as read.
db.markAllDmsRead();
setupAdapter(); // Make sure call bindFooterButtonEvent first
boolean shouldRetrieve = false;
long lastRefreshTime = mPreferences.getLong(
Preferences.LAST_DM_REFRESH_KEY, 0);
long nowTime = DateTimeHelper.getNowTime();
long diff = nowTime - lastRefreshTime;
Log.d(TAG, "Last refresh was " + diff + " ms ago.");
if (diff > REFRESH_THRESHOLD) {
shouldRetrieve = true;
} else if (isTrue(savedInstanceState, SIS_RUNNING_KEY)) {
// Check to see if it was running a send or retrieve task.
// It makes no sense to resend the send request (don't want dupes)
// so we instead retrieve (refresh) to see if the message has
// posted.
Log.d(TAG,
"Was last running a retrieve or send task. Let's refresh.");
shouldRetrieve = true;
}
if (shouldRetrieve) {
doRetrieve();
}
// Want to be able to focus on the items with the trackball.
// That way, we can navigate up and down by changing item focus.
mTweetList.setItemsCanFocus(true);
return true;
}else{
return false;
}
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
private static final String SIS_RUNNING_KEY = "running";
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
mRetrieveTask.cancel(true);
}
if (mDeleteTask != null
&& mDeleteTask.getStatus() == GenericTask.Status.RUNNING) {
mDeleteTask.cancel(true);
}
super.onDestroy();
}
// UI helpers.
private void bindFooterButtonEvent() {
inbox = (Button) findViewById(R.id.inbox);
sendbox = (Button) findViewById(R.id.sendbox);
newMsg = (Button) findViewById(R.id.new_message);
inbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mDMType != DM_TYPE_INBOX) {
mDMType = DM_TYPE_INBOX;
inbox.setEnabled(false);
sendbox.setEnabled(true);
mTweetList.setAdapter(mInboxAdapter);
mInboxAdapter.refresh();
}
}
});
sendbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mDMType != DM_TYPE_SENDBOX) {
mDMType = DM_TYPE_SENDBOX;
inbox.setEnabled(true);
sendbox.setEnabled(false);
mTweetList.setAdapter(mSendboxAdapter);
mSendboxAdapter.refresh();
}
}
});
newMsg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(DmActivity.this, WriteDmActivity.class);
intent.putExtra("reply_to_id", 0); // TODO: 传入实际的reply_to_id
startActivity(intent);
}
});
}
private void setupAdapter() {
Cursor cursor = getDb().fetchAllDms(-1);
startManagingCursor(cursor);
mAdapter = new Adapter(this, cursor);
Cursor inboxCursor = getDb().fetchInboxDms();
startManagingCursor(inboxCursor);
mInboxAdapter = new Adapter(this, inboxCursor);
Cursor sendboxCursor = getDb().fetchSendboxDms();
startManagingCursor(sendboxCursor);
mSendboxAdapter = new Adapter(this, sendboxCursor);
mTweetList.setAdapter(mInboxAdapter);
registerForContextMenu(mTweetList);
inbox.setEnabled(false);
}
private class DmRetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams...params) {
List<DirectMessage> dmList;
ArrayList<Dm> dms = new ArrayList<Dm>();
TwitterDatabase db = getDb();
//ImageManager imageManager = getImageManager();
String maxId = db.fetchMaxDmId(false);
HashSet<String> imageUrls = new HashSet<String>();
try {
if (maxId != null) {
Paging paging = new Paging(maxId);
dmList = getApi().getDirectMessages(paging);
} else {
dmList = getApi().getDirectMessages();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, dmList));
for (DirectMessage directMessage : dmList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Dm dm;
dm = Dm.create(directMessage, false);
dms.add(dm);
imageUrls.add(dm.profileImageUrl);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
maxId = db.fetchMaxDmId(true);
try {
if (maxId != null) {
Paging paging = new Paging(maxId);
dmList = getApi().getSentDirectMessages(paging);
} else {
dmList = getApi().getSentDirectMessages();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
for (DirectMessage directMessage : dmList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Dm dm;
dm = Dm.create(directMessage, true);
dms.add(dm);
imageUrls.add(dm.profileImageUrl);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
db.addDms(dms, false);
// if (isCancelled()) {
// return TaskResult.CANCELLED;
// }
//
// publishProgress(null);
//
// for (String imageUrl : imageUrls) {
// if (!Utils.isEmpty(imageUrl)) {
// // Fetch image to cache.
// try {
// imageManager.put(imageUrl);
// } catch (IOException e) {
// Log.e(TAG, e.getMessage(), e);
// }
// }
//
// if (isCancelled()) {
// return TaskResult.CANCELLED;
// }
// }
return TaskResult.OK;
}
}
private static class Adapter extends CursorAdapter {
public Adapter(Context context, Cursor cursor) {
super(context, cursor);
mInflater = LayoutInflater.from(context);
// TODO: 可使用:
//DM dm = MessageTable.parseCursor(cursor);
mUserTextColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_USER_SCREEN_NAME);
mTextColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_TEXT);
mProfileImageUrlColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_PROFILE_IMAGE_URL);
mCreatedAtColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_CREATED_AT);
mIsSentColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_IS_SENT);
}
private LayoutInflater mInflater;
private int mUserTextColumn;
private int mTextColumn;
private int mProfileImageUrlColumn;
private int mIsSentColumn;
private int mCreatedAtColumn;
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater.inflate(R.layout.direct_message, parent,
false);
ViewHolder holder = new ViewHolder();
holder.userText = (TextView) view
.findViewById(R.id.tweet_user_text);
holder.tweetText = (TextView) view.findViewById(R.id.tweet_text);
holder.profileImage = (ImageView) view
.findViewById(R.id.profile_image);
holder.metaText = (TextView) view
.findViewById(R.id.tweet_meta_text);
view.setTag(holder);
return view;
}
class ViewHolder {
public TextView userText;
public TextView tweetText;
public ImageView profileImage;
public TextView metaText;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = (ViewHolder) view.getTag();
int isSent = cursor.getInt(mIsSentColumn);
String user = cursor.getString(mUserTextColumn);
if (0 == isSent) {
holder.userText.setText(context
.getString(R.string.direct_message_label_from_prefix)
+ user);
} else {
holder.userText.setText(context
.getString(R.string.direct_message_label_to_prefix)
+ user);
}
TextHelper.setTweetText(holder.tweetText, cursor.getString(mTextColumn));
String profileImageUrl = cursor.getString(mProfileImageUrlColumn);
if (!TextUtils.isEmpty(profileImageUrl)) {
holder.profileImage
.setImageBitmap(TwitterApplication.mImageLoader
.get(profileImageUrl, new ImageLoaderCallback(){
@Override
public void refresh(String url,
Bitmap bitmap) {
Adapter.this.refresh();
}
}));
}
try {
holder.metaText.setText(DateTimeHelper
.getRelativeDate(TwitterDatabase.DB_DATE_FORMATTER
.parse(cursor.getString(mCreatedAtColumn))));
} catch (ParseException e) {
Log.w(TAG, "Invalid created at data.");
}
}
public void refresh() {
getCursor().requery();
}
}
// Menu.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// FIXME: 将刷新功能绑定到顶部的刷新按钮上,主菜单中的刷新选项已删除
// case OPTIONS_MENU_ID_REFRESH:
// doRetrieve();
// return true;
case OPTIONS_MENU_ID_TWEETS:
launchActivity(TwitterActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_REPLIES:
launchActivity(MentionActivity.createIntent(this));
return true;
}
return super.onOptionsItemSelected(item);
}
private static final int CONTEXT_REPLY_ID = 0;
private static final int CONTEXT_DELETE_ID = 1;
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, CONTEXT_REPLY_ID, 0, R.string.cmenu_reply);
menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
Cursor cursor = (Cursor) mAdapter.getItem(info.position);
if (cursor == null) {
Log.w(TAG, "Selected item not available.");
return super.onContextItemSelected(item);
}
switch (item.getItemId()) {
case CONTEXT_REPLY_ID:
String user_id = cursor.getString(cursor
.getColumnIndexOrThrow(MessageTable.FIELD_USER_ID));
Intent intent = WriteDmActivity.createIntent(user_id);
startActivity(intent);
return true;
case CONTEXT_DELETE_ID:
int idIndex = cursor.getColumnIndexOrThrow(MessageTable._ID);
String id = cursor.getString(idIndex);
doDestroy(id);
return true;
default:
return super.onContextItemSelected(item);
}
}
private void doDestroy(String id) {
Log.d(TAG, "Attempting delete.");
if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING){
return;
}else{
mDeleteTask = new DmDeleteTask();
mDeleteTask.setListener(mDeleteTaskListener);
TaskParams params = new TaskParams();
params.put("id", id);
mDeleteTask.execute(params);
}
}
private class DmDeleteTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams...params) {
TaskParams param = params[0];
try {
String id = param.getString("id");
DirectMessage directMessage = getApi().destroyDirectMessage(id);
Dm.create(directMessage, false);
getDb().deleteDm(id);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
if (isCancelled()) {
return TaskResult.CANCELLED;
}
return TaskResult.OK;
}
}
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING){
return;
}else{
mRetrieveTask = new DmRetrieveTask();
mRetrieveTask.setFeedback(mFeedback);
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute();
}
}
public void goTop() {
mTweetList.setSelection(0);
}
public void draw() {
mAdapter.refresh();
mInboxAdapter.refresh();
mSendboxAdapter.refresh();
}
private void updateProgress(String msg) {
mProgressText.setText(msg);
}
}
| Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity;
//TODO: 数据来源换成 getFavorites()
public class FavoritesActivity extends TwitterCursorBaseActivity {
private static final String TAG = "FavoritesActivity";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FAVORITES";
private static final String USER_ID = "userid";
private static final String USER_NAME = "userName";
private static final int DIALOG_WRITE_ID = 0;
private String userId = null;
private String userName = null;
public static Intent createIntent(String userId, String userName) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(USER_ID, userId);
intent.putExtra(USER_NAME, userName);
return intent;
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)){
mNavbar.setHeaderTitle(getActivityTitle());
return true;
}else{
return false;
}
}
public static Intent createNewTaskIntent(String userId, String userName) {
Intent intent = createIntent(userId, userName);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
// Menu.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
protected Cursor fetchMessages() {
// TODO Auto-generated method stub
return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_FAVORITE);
}
@Override
protected String getActivityTitle() {
// TODO Auto-generated method stub
String template = getString(R.string.page_title_favorites);
String who;
if (getUserId().equals(TwitterApplication.getMyselfId())){
who = "我";
}else{
who = getUserName();
}
return MessageFormat.format(template, who);
}
@Override
protected void markAllRead() {
// TODO Auto-generated method stub
getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_FAVORITE);
}
// hasRetrieveListTask interface
@Override
public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) {
return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_FAVORITE, isUnread);
}
@Override
public String fetchMaxId() {
return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_FAVORITE);
}
@Override
public List<Status> getMessageSinceId(String maxId) throws HttpException {
if (maxId != null){
return getApi().getFavorites(getUserId(), new Paging(maxId));
}else{
return getApi().getFavorites(getUserId());
}
}
@Override
public String fetchMinId() {
return getDb().fetchMinTweetId(getUserId(), StatusTable.TYPE_FAVORITE);
}
@Override
public List<Status> getMoreMessageFromId(String minId)
throws HttpException {
Paging paging = new Paging(1, 20);
paging.setMaxId(minId);
return getApi().getFavorites(getUserId(), paging);
}
@Override
public int getDatabaseType() {
return StatusTable.TYPE_FAVORITE;
}
@Override
public String getUserId() {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null){
userId = extras.getString(USER_ID);
} else {
userId = TwitterApplication.getMyselfId();
}
return userId;
}
public String getUserName(){
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null){
userName = extras.getString(USER_NAME);
} else {
userName = TwitterApplication.getMyselfName();
}
return userName;
}
} | Java |
package com.ch_linghu.fanfoudroid;
import java.text.MessageFormat;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.UserArrayBaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter;
public class FollowingActivity extends UserArrayBaseActivity {
private ListView mUserList;
private UserArrayAdapter mAdapter;
private String userId;
private String userName;
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FOLLOWING";
private static final String USER_ID = "userId";
private static final String USER_NAME = "userName";
private int currentPage=1;
String myself="";
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
this.userId = extras.getString(USER_ID);
this.userName = extras.getString(USER_NAME);
} else {
// 获取登录用户id
userId=TwitterApplication.getMyselfId();
userName = TwitterApplication.getMyselfName();
}
if(super._onCreate(savedInstanceState)){
myself = TwitterApplication.getMyselfId();
if(getUserId()==myself){
mNavbar.setHeaderTitle(MessageFormat.format(
getString(R.string.profile_friends_count_title), "我"));
} else {
mNavbar.setHeaderTitle(MessageFormat.format(
getString(R.string.profile_friends_count_title), userName));
}
return true;
}else{
return false;
}
}
/*
* 添加取消关注按钮
* @see com.ch_linghu.fanfoudroid.ui.base.UserListBaseActivity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo)
*/
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if(getUserId()==myself){
AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
User user = getContextItemUser(info.position);
menu.add(0,CONTENT_DEL_FRIEND,0,getResources().getString(R.string.cmenu_user_addfriend_prefix)+user.screenName+getResources().getString(R.string.cmenu_user_friend_suffix));
}
}
public static Intent createIntent(String userId, String userName) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(USER_ID, userId);
intent.putExtra(USER_NAME, userName);
return intent;
}
@Override
public Paging getNextPage() {
currentPage+=1;
return new Paging(currentPage);
}
@Override
protected String getUserId() {
return this.userId;
}
@Override
public Paging getCurrentPage() {
return new Paging(this.currentPage);
}
@Override
protected List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers(
String userId, Paging page) throws HttpException {
return getApi().getFriendsStatuses(userId, page);
}
}
| Java |
package com.ch_linghu.fanfoudroid;
import java.text.MessageFormat;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.db.UserInfoTable;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
/**
*
* @author Dino 2011-02-26
*/
// public class ProfileActivity extends WithHeaderActivity {
public class ProfileActivity extends BaseActivity {
private static final String TAG = "ProfileActivity";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.PROFILE";
private static final String STATUS_COUNT = "status_count";
private static final String EXTRA_USER = "user";
private static final String FANFOUROOT = "http://fanfou.com/";
private static final String USER_ID = "userid";
private static final String USER_NAME = "userName";
private GenericTask profileInfoTask;// 获取用户信息
private GenericTask setFollowingTask;
private GenericTask cancelFollowingTask;
private String userId;
private String userName;
private String myself;
private User profileInfo;// 用户信息
private ImageView profileImageView;// 头像
private TextView profileName;// 名称
private TextView profileScreenName;// 昵称
private TextView userLocation;// 地址
private TextView userUrl;// url
private TextView userInfo;// 自述
private TextView friendsCount;// 好友
private TextView followersCount;// 收听
private TextView statusCount;// 消息
private TextView favouritesCount;// 收藏
private TextView isFollowingText;// 是否关注
private Button followingBtn;// 收听/取消关注按钮
private Button sendMentionBtn;// 发送留言按钮
private Button sendDmBtn;// 发送私信按钮
private ProgressDialog dialog; // 请稍候
private RelativeLayout friendsLayout;
private LinearLayout followersLayout;
private LinearLayout statusesLayout;
private LinearLayout favouritesLayout;
private NavBar mNavBar;
private Feedback mFeedback;
private TwitterDatabase db;
public static Intent createIntent(String userId) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.putExtra(USER_ID, userId);
return intent;
}
private ImageLoaderCallback callback = new ImageLoaderCallback() {
@Override
public void refresh(String url, Bitmap bitmap) {
profileImageView.setImageBitmap(bitmap);
}
};
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "OnCreate start");
if (super._onCreate(savedInstanceState)) {
setContentView(R.layout.profile);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
myself = TwitterApplication.getMyselfId();
if (extras != null) {
this.userId = extras.getString(USER_ID);
this.userName = extras.getString(USER_NAME);
} else {
this.userId = myself;
this.userName = TwitterApplication.getMyselfName();
}
Uri data = intent.getData();
if (data != null) {
userId = data.getLastPathSegment();
}
// 初始化控件
initControls();
Log.d(TAG, "the userid is " + userId);
db = this.getDb();
draw();
return true;
} else {
return false;
}
}
private void initControls() {
mNavBar = new NavBar(NavBar.HEADER_STYLE_HOME, this);
mNavBar.setHeaderTitle("");
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
sendMentionBtn = (Button) findViewById(R.id.sendmetion_btn);
sendDmBtn = (Button) findViewById(R.id.senddm_btn);
profileImageView = (ImageView) findViewById(R.id.profileimage);
profileName = (TextView) findViewById(R.id.profilename);
profileScreenName = (TextView) findViewById(R.id.profilescreenname);
userLocation = (TextView) findViewById(R.id.user_location);
userUrl = (TextView) findViewById(R.id.user_url);
userInfo = (TextView) findViewById(R.id.tweet_user_info);
friendsCount = (TextView) findViewById(R.id.friends_count);
followersCount = (TextView) findViewById(R.id.followers_count);
TextView friendsCountTitle = (TextView) findViewById(R.id.friends_count_title);
TextView followersCountTitle = (TextView) findViewById(R.id.followers_count_title);
String who;
if (userId.equals(myself)) {
who = "我";
} else {
who = "ta";
}
friendsCountTitle.setText(MessageFormat.format(
getString(R.string.profile_friends_count_title), who));
followersCountTitle.setText(MessageFormat.format(
getString(R.string.profile_followers_count_title), who));
statusCount = (TextView) findViewById(R.id.statuses_count);
favouritesCount = (TextView) findViewById(R.id.favourites_count);
friendsLayout = (RelativeLayout) findViewById(R.id.friendsLayout);
followersLayout = (LinearLayout) findViewById(R.id.followersLayout);
statusesLayout = (LinearLayout) findViewById(R.id.statusesLayout);
favouritesLayout = (LinearLayout) findViewById(R.id.favouritesLayout);
isFollowingText = (TextView) findViewById(R.id.isfollowing_text);
followingBtn = (Button) findViewById(R.id.following_btn);
// 为按钮面板添加事件
friendsLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在没有得到profileInfo时,不允许点击事件生效
if (profileInfo == null) {
return;
}
String showName;
if (!TextUtils.isEmpty(profileInfo.getScreenName())) {
showName = profileInfo.getScreenName();
} else {
showName = profileInfo.getName();
}
Intent intent = FollowingActivity
.createIntent(userId, showName);
intent.setClass(ProfileActivity.this, FollowingActivity.class);
startActivity(intent);
}
});
followersLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在没有得到profileInfo时,不允许点击事件生效
if (profileInfo == null) {
return;
}
String showName;
if (!TextUtils.isEmpty(profileInfo.getScreenName())) {
showName = profileInfo.getScreenName();
} else {
showName = profileInfo.getName();
}
Intent intent = FollowersActivity
.createIntent(userId, showName);
intent.setClass(ProfileActivity.this, FollowersActivity.class);
startActivity(intent);
}
});
statusesLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在没有得到profileInfo时,不允许点击事件生效
if (profileInfo == null) {
return;
}
String showName;
if (!TextUtils.isEmpty(profileInfo.getScreenName())) {
showName = profileInfo.getScreenName();
} else {
showName = profileInfo.getName();
}
Intent intent = UserTimelineActivity.createIntent(
profileInfo.getId(), showName);
launchActivity(intent);
}
});
favouritesLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在没有得到profileInfo时,不允许点击事件生效
if (profileInfo == null) {
return;
}
Intent intent = FavoritesActivity.createIntent(userId,
profileInfo.getName());
intent.setClass(ProfileActivity.this, FavoritesActivity.class);
startActivity(intent);
}
});
// 刷新
View.OnClickListener refreshListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
doGetProfileInfo();
}
};
mNavBar.getRefreshButton().setOnClickListener(refreshListener);
}
private void draw() {
Log.d(TAG, "draw");
bindProfileInfo();
// doGetProfileInfo();
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume.");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart.");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop.");
}
/**
* 从数据库获取,如果数据库不存在则创建
*/
private void bindProfileInfo() {
dialog = ProgressDialog.show(ProfileActivity.this, "请稍候", "正在加载信息...");
if (null != db && db.existsUser(userId)) {
Cursor cursor = db.getUserInfoById(userId);
profileInfo = User.parseUser(cursor);
cursor.close();
if (profileInfo == null) {
Log.w(TAG, "cannot get userinfo from userinfotable the id is"
+ userId);
}
bindControl();
if (dialog != null) {
dialog.dismiss();
}
} else {
doGetProfileInfo();
}
}
private void doGetProfileInfo() {
mFeedback.start("");
if (profileInfoTask != null
&& profileInfoTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
profileInfoTask = new GetProfileTask();
profileInfoTask.setListener(profileInfoTaskListener);
TaskParams params = new TaskParams();
profileInfoTask.execute(params);
}
}
private void bindControl() {
if (profileInfo.getId().equals(myself)) {
sendMentionBtn.setVisibility(View.GONE);
sendDmBtn.setVisibility(View.GONE);
} else {
// 发送留言
sendMentionBtn.setVisibility(View.VISIBLE);
sendMentionBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = WriteActivity.createNewTweetIntent(String
.format("@%s ", profileInfo.getScreenName()));
startActivity(intent);
}
});
// 发送私信
sendDmBtn.setVisibility(View.VISIBLE);
sendDmBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = WriteDmActivity.createIntent(profileInfo
.getId());
startActivity(intent);
}
});
}
if (userId.equals(myself)) {
mNavBar.setHeaderTitle("我"
+ getString(R.string.cmenu_user_profile_prefix));
} else {
mNavBar.setHeaderTitle(profileInfo.getScreenName()
+ getString(R.string.cmenu_user_profile_prefix));
}
profileImageView
.setImageBitmap(TwitterApplication.mImageLoader
.get(profileInfo.getProfileImageURL().toString(),
callback));
profileName.setText(profileInfo.getId());
profileScreenName.setText(profileInfo.getScreenName());
if (profileInfo.getId().equals(myself)) {
isFollowingText.setText(R.string.profile_isyou);
followingBtn.setVisibility(View.GONE);
} else if (profileInfo.isFollowing()) {
isFollowingText.setText(R.string.profile_isfollowing);
followingBtn.setVisibility(View.VISIBLE);
followingBtn.setText(R.string.user_label_unfollow);
followingBtn.setOnClickListener(cancelFollowingListener);
followingBtn.setCompoundDrawablesWithIntrinsicBounds(getResources()
.getDrawable(R.drawable.ic_unfollow), null, null, null);
} else {
isFollowingText.setText(R.string.profile_notfollowing);
followingBtn.setVisibility(View.VISIBLE);
followingBtn.setText(R.string.user_label_follow);
followingBtn.setOnClickListener(setfollowingListener);
followingBtn.setCompoundDrawablesWithIntrinsicBounds(getResources()
.getDrawable(R.drawable.ic_follow), null, null, null);
}
String location = profileInfo.getLocation();
if (location == null || location.length() == 0) {
location = getResources().getString(R.string.profile_location_null);
}
userLocation.setText(location);
if (profileInfo.getURL() != null) {
userUrl.setText(profileInfo.getURL().toString());
} else {
userUrl.setText(FANFOUROOT + profileInfo.getId());
}
String description = profileInfo.getDescription();
if (description == null || description.length() == 0) {
description = getResources().getString(
R.string.profile_description_null);
}
userInfo.setText(description);
friendsCount.setText(String.valueOf(profileInfo.getFriendsCount()));
followersCount.setText(String.valueOf(profileInfo.getFollowersCount()));
statusCount.setText(String.valueOf(profileInfo.getStatusesCount()));
favouritesCount
.setText(String.valueOf(profileInfo.getFavouritesCount()));
}
private TaskListener profileInfoTaskListener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
// 加载成功
if (result == TaskResult.OK) {
mFeedback.success("");
// 绑定控件
bindControl();
if (dialog != null) {
dialog.dismiss();
}
}
}
@Override
public String getName() {
return "GetProfileInfo";
}
};
/**
* 更新数据库中的用户
*
* @return
*/
private boolean updateUser() {
ContentValues v = new ContentValues();
v.put(BaseColumns._ID, profileInfo.getName());
v.put(UserInfoTable.FIELD_USER_NAME, profileInfo.getName());
v.put(UserInfoTable.FIELD_USER_SCREEN_NAME, profileInfo.getScreenName());
v.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, profileInfo
.getProfileImageURL().toString());
v.put(UserInfoTable.FIELD_LOCALTION, profileInfo.getLocation());
v.put(UserInfoTable.FIELD_DESCRIPTION, profileInfo.getDescription());
v.put(UserInfoTable.FIELD_PROTECTED, profileInfo.isProtected());
v.put(UserInfoTable.FIELD_FOLLOWERS_COUNT,
profileInfo.getFollowersCount());
v.put(UserInfoTable.FIELD_LAST_STATUS, profileInfo.getStatusSource());
v.put(UserInfoTable.FIELD_FRIENDS_COUNT, profileInfo.getFriendsCount());
v.put(UserInfoTable.FIELD_FAVORITES_COUNT,
profileInfo.getFavouritesCount());
v.put(UserInfoTable.FIELD_STATUSES_COUNT,
profileInfo.getStatusesCount());
v.put(UserInfoTable.FIELD_FOLLOWING, profileInfo.isFollowing());
if (profileInfo.getURL() != null) {
v.put(UserInfoTable.FIELD_URL, profileInfo.getURL().toString());
}
return db.updateUser(profileInfo.getId(), v);
}
/**
* 获取用户信息task
*
* @author Dino
*
*/
private class GetProfileTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
Log.v(TAG, "get profile task");
try {
profileInfo = getApi().showUser(userId);
mFeedback.update(80);
if (profileInfo != null) {
if (null != db && !db.existsUser(userId)) {
com.ch_linghu.fanfoudroid.data.User userinfodb = profileInfo
.parseUser();
db.createUserInfo(userinfodb);
} else {
// 更新用户
updateUser();
}
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage());
return TaskResult.FAILED;
}
mFeedback.update(99);
return TaskResult.OK;
}
}
/**
* 设置关注监听
*/
private OnClickListener setfollowingListener = new OnClickListener() {
@Override
public void onClick(View v) {
Builder diaBuilder = new AlertDialog.Builder(ProfileActivity.this)
.setTitle("关注提示").setMessage("确实要添加关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (setFollowingTask != null
&& setFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
setFollowingTask = new SetFollowingTask();
setFollowingTask
.setListener(setFollowingTaskLinstener);
TaskParams params = new TaskParams();
setFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
};
/*
* 取消关注监听
*/
private OnClickListener cancelFollowingListener = new OnClickListener() {
@Override
public void onClick(View v) {
Builder diaBuilder = new AlertDialog.Builder(ProfileActivity.this)
.setTitle("关注提示").setMessage("确实要取消关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (cancelFollowingTask != null
&& cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
cancelFollowingTask = new CancelFollowingTask();
cancelFollowingTask
.setListener(cancelFollowingTaskLinstener);
TaskParams params = new TaskParams();
cancelFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
};
/**
* 设置关注
*
* @author Dino
*
*/
private class SetFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
getApi().createFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener setFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
followingBtn.setText("取消关注");
isFollowingText.setText(getResources().getString(
R.string.profile_isfollowing));
followingBtn.setOnClickListener(cancelFollowingListener);
Toast.makeText(getBaseContext(), "关注成功", Toast.LENGTH_SHORT)
.show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(getBaseContext(), "关注失败", Toast.LENGTH_SHORT)
.show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
/**
* 取消关注
*
* @author Dino
*
*/
private class CancelFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
getApi().destroyFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener cancelFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
followingBtn.setText("添加关注");
isFollowingText.setText(getResources().getString(
R.string.profile_notfollowing));
followingBtn.setOnClickListener(setfollowingListener);
Toast.makeText(getBaseContext(), "取消关注成功", Toast.LENGTH_SHORT)
.show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(getBaseContext(), "取消关注失败", Toast.LENGTH_SHORT)
.show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
}
| Java |
package com.ch_linghu.fanfoudroid.dao;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;
import com.ch_linghu.fanfoudroid.dao.SQLiteTemplate.RowMapper;
import com.ch_linghu.fanfoudroid.data2.Photo;
import com.ch_linghu.fanfoudroid.data2.Status;
import com.ch_linghu.fanfoudroid.data2.User;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.db2.FanContent;
import com.ch_linghu.fanfoudroid.db2.FanContent.StatusesPropertyTable;
import com.ch_linghu.fanfoudroid.db2.FanDatabase;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.db2.FanContent.*;
public class StatusDAO {
private static final String TAG = "StatusDAO";
private SQLiteTemplate mSqlTemplate;
public StatusDAO(Context context) {
mSqlTemplate = new SQLiteTemplate(FanDatabase.getInstance(context)
.getSQLiteOpenHelper());
}
/**
* Insert a Status
*
* 若报 SQLiteconstraintexception 异常, 检查是否某not null字段为空
*
* @param status
* @param isUnread
* @return
*/
public long insertStatus(Status status) {
if (!isExists(status)) {
return mSqlTemplate.getDb(true).insert(StatusesTable.TABLE_NAME, null,
statusToContentValues(status));
} else {
Log.e(TAG, status.getId() + " is exists.");
return -1;
}
}
// TODO:
public int insertStatuses(List<Status> statuses) {
int result = 0;
SQLiteDatabase db = mSqlTemplate.getDb(true);
try {
db.beginTransaction();
for (int i = statuses.size() - 1; i >= 0; i--) {
Status status = statuses.get(i);
long id = db.insertWithOnConflict(StatusesTable.TABLE_NAME, null,
statusToContentValues(status),
SQLiteDatabase.CONFLICT_IGNORE);
if (-1 == id) {
Log.e(TAG, "cann't insert the tweet : " + status.toString());
} else {
++result;
Log.v(TAG, String.format(
"Insert a status into database : %s",
status.toString()));
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
return result;
}
/**
* Delete a status
*
* @param statusId
* @param owner_id
* owner id
* @param type
* status type
* @return
* @see StatusDAO#deleteStatus(Status)
*/
public int deleteStatus(String statusId, String owner_id, int type) {
//FIXME: 数据模型改变后这里的逻辑需要完全重写,目前仅保证编译可通过
String where = StatusesTable.Columns.ID + " =? ";
String[] binds;
if (!TextUtils.isEmpty(owner_id)) {
where += " AND " + StatusesPropertyTable.Columns.OWNER_ID + " = ? ";
binds = new String[] { statusId, owner_id };
} else {
binds = new String[] { statusId };
}
if (-1 != type) {
where += " AND " + StatusesPropertyTable.Columns.TYPE + " = " + type;
}
return mSqlTemplate.getDb(true).delete(StatusesTable.TABLE_NAME, where.toString(),
binds);
}
/**
* Delete a Status
*
* @param status
* @return
* @see StatusDAO#deleteStatus(String, String, int)
*/
public int deleteStatus(Status status) {
return deleteStatus(status.getId(), status.getOwnerId(),
status.getType());
}
/**
* Find a status by status ID
*
* @param statusId
* @return
*/
public Status fetchStatus(String statusId) {
return mSqlTemplate.queryForObject(mRowMapper, StatusesTable.TABLE_NAME, null,
StatusesTable.Columns.ID + " = ?", new String[] { statusId }, null,
null, "created_at DESC", "1");
}
/**
* Find user's statuses
*
* @param userId
* user id
* @param statusType
* status type, see {@link StatusTable#TYPE_USER}...
* @return list of statuses
*/
public List<Status> fetchStatuses(String userId, int statusType) {
return mSqlTemplate.queryForList(mRowMapper, FanContent.StatusesTable.TABLE_NAME, null,
StatusesPropertyTable.Columns.OWNER_ID + " = ? AND " + StatusesPropertyTable.Columns.TYPE
+ " = " + statusType, new String[] { userId }, null,
null, "created_at DESC", null);
}
/**
* @see StatusDAO#fetchStatuses(String, int)
*/
public List<Status> fetchStatuses(String userId, String statusType) {
return fetchStatuses(userId, Integer.parseInt(statusType));
}
/**
* Update by using {@link ContentValues}
*
* @param statusId
* @param newValues
* @return
*/
public int updateStatus(String statusId, ContentValues values) {
return mSqlTemplate.updateById(FanContent.StatusesTable.TABLE_NAME, statusId, values);
}
/**
* Update by using {@link Status}
*
* @param status
* @return
*/
public int updateStatus(Status status) {
return updateStatus(status.getId(), statusToContentValues(status));
}
/**
* Check if status exists
*
* FIXME: 取消使用Query
*
* @param status
* @return
*/
public boolean isExists(Status status) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT COUNT(*) FROM ").append(FanContent.StatusesTable.TABLE_NAME)
.append(" WHERE ").append(StatusesTable.Columns.ID).append(" =? AND ")
.append(StatusesPropertyTable.Columns.OWNER_ID).append(" =? AND ")
.append(StatusesPropertyTable.Columns.TYPE).append(" = ")
.append(status.getType());
return mSqlTemplate.isExistsBySQL(sql.toString(),
new String[] { status.getId(), status.getUser().getId() });
}
/**
* Status -> ContentValues
*
* @param status
* @param isUnread
* @return
*/
private ContentValues statusToContentValues(Status status) {
final ContentValues v = new ContentValues();
v.put(StatusesTable.Columns.ID, status.getId());
v.put(StatusesPropertyTable.Columns.TYPE, status.getType());
v.put(StatusesTable.Columns.TEXT, status.getText());
v.put(StatusesPropertyTable.Columns.OWNER_ID, status.getOwnerId());
v.put(StatusesTable.Columns.FAVORITED, status.isFavorited() + "");
v.put(StatusesTable.Columns.TRUNCATED, status.isTruncated()); // TODO:
v.put(StatusesTable.Columns.IN_REPLY_TO_STATUS_ID, status.getInReplyToStatusId());
v.put(StatusesTable.Columns.IN_REPLY_TO_USER_ID, status.getInReplyToUserId());
// v.put(StatusTable.Columns.IN_REPLY_TO_SCREEN_NAME,
// status.getInReplyToScreenName());
// v.put(IS_REPLY, status.isReply());
v.put(StatusesTable.Columns.CREATED_AT,
TwitterDatabase.DB_DATE_FORMATTER.format(status.getCreatedAt()));
v.put(StatusesTable.Columns.SOURCE, status.getSource());
// v.put(StatusTable.Columns.IS_UNREAD, status.isUnRead());
final User user = status.getUser();
if (user != null) {
v.put(UserTable.Columns.USER_ID, user.getId());
v.put(UserTable.Columns.SCREEN_NAME, user.getScreenName());
v.put(UserTable.Columns.PROFILE_IMAGE_URL, user.getProfileImageUrl());
}
final Photo photo = status.getPhotoUrl();
/*if (photo != null) {
v.put(StatusTable.Columns.PIC_THUMB, photo.getThumburl());
v.put(StatusTable.Columns.PIC_MID, photo.getImageurl());
v.put(StatusTable.Columns.PIC_ORIG, photo.getLargeurl());
}*/
return v;
}
private static final RowMapper<Status> mRowMapper = new RowMapper<Status>() {
@Override
public Status mapRow(Cursor cursor, int rowNum) {
Photo photo = new Photo();
/*photo.setImageurl(cursor.getString(cursor
.getColumnIndex(StatusTable.Columns.PIC_MID)));
photo.setLargeurl(cursor.getString(cursor
.getColumnIndex(StatusTable.Columns.PIC_ORIG)));
photo.setThumburl(cursor.getString(cursor
.getColumnIndex(StatusTable.Columns.PIC_THUMB)));
*/
User user = new User();
user.setScreenName(cursor.getString(cursor
.getColumnIndex(UserTable.Columns.SCREEN_NAME)));
user.setId(cursor.getString(cursor
.getColumnIndex(UserTable.Columns.USER_ID)));
user.setProfileImageUrl(cursor.getString(cursor
.getColumnIndex(UserTable.Columns.PROFILE_IMAGE_URL)));
Status status = new Status();
status.setPhotoUrl(photo);
status.setUser(user);
status.setOwnerId(cursor.getString(cursor
.getColumnIndex(StatusesPropertyTable.Columns.OWNER_ID)));
// TODO: 将数据库中的statusType改成Int类型
status.setType(cursor.getInt(cursor
.getColumnIndex(StatusesPropertyTable.Columns.TYPE)));
status.setId(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.ID)));
status.setCreatedAt(DateTimeHelper.parseDateTimeFromSqlite(cursor
.getString(cursor.getColumnIndex(StatusesTable.Columns.CREATED_AT))));
// TODO: 更改favorite 在数据库类型为boolean后改为 " != 0 "
status.setFavorited(cursor.getString(
cursor.getColumnIndex(StatusesTable.Columns.FAVORITED))
.equals("true"));
status.setText(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.TEXT)));
status.setSource(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.SOURCE)));
// status.setInReplyToScreenName(cursor.getString(cursor
// .getColumnIndex(StatusTable.IN_REPLY_TO_SCREEN_NAME)));
status.setInReplyToStatusId(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.IN_REPLY_TO_STATUS_ID)));
status.setInReplyToUserId(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.IN_REPLY_TO_USER_ID)));
status.setTruncated(cursor.getInt(cursor
.getColumnIndex(StatusesTable.Columns.TRUNCATED)) != 0);
// status.setUnRead(cursor.getInt(cursor
// .getColumnIndex(StatusTable.Columns.IS_UNREAD)) != 0);
return status;
}
};
}
| Java |
package com.ch_linghu.fanfoudroid.dao;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Database Helper
*
* @see SQLiteDatabase
*/
public class SQLiteTemplate {
/**
* Default Primary key
*/
protected String mPrimaryKey = "_id";
/**
* SQLiteDatabase Open Helper
*/
protected SQLiteOpenHelper mDatabaseOpenHelper;
/**
* Construct
*
* @param databaseOpenHelper
*/
public SQLiteTemplate(SQLiteOpenHelper databaseOpenHelper) {
mDatabaseOpenHelper = databaseOpenHelper;
}
/**
* Construct
*
* @param databaseOpenHelper
* @param primaryKey
*/
public SQLiteTemplate(SQLiteOpenHelper databaseOpenHelper, String primaryKey) {
this(databaseOpenHelper);
setPrimaryKey(primaryKey);
}
/**
* 根据某一个字段和值删除一行数据, 如 name="jack"
*
* @param table
* @param field
* @param value
* @return
*/
public int deleteByField(String table, String field, String value) {
return getDb(true).delete(table, field + "=?", new String[] { value });
}
/**
* 根据主键删除一行数据
*
* @param table
* @param id
* @return
*/
public int deleteById(String table, String id) {
return deleteByField(table, mPrimaryKey, id);
}
/**
* 根据主键更新一行数据
*
* @param table
* @param id
* @param values
* @return
*/
public int updateById(String table, String id, ContentValues values) {
return getDb(true).update(table, values, mPrimaryKey + "=?",
new String[] { id });
}
/**
* 根据主键查看某条数据是否存在
*
* @param table
* @param id
* @return
*/
public boolean isExistsById(String table, String id) {
return isExistsByField(table, mPrimaryKey, id);
}
/**
* 根据某字段/值查看某条数据是否存在
*
* @param status
* @return
*/
public boolean isExistsByField(String table, String field, String value) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT COUNT(*) FROM ").append(table).append(" WHERE ")
.append(field).append(" =?");
return isExistsBySQL(sql.toString(), new String[] { value });
}
/**
* 使用SQL语句查看某条数据是否存在
*
* @param sql
* @param selectionArgs
* @return
*/
public boolean isExistsBySQL(String sql, String[] selectionArgs) {
boolean result = false;
final Cursor c = getDb(false).rawQuery(sql, selectionArgs);
try {
if (c.moveToFirst()) {
result = (c.getInt(0) > 0);
}
} finally {
c.close();
}
return result;
}
/**
* Query for cursor
*
* @param <T>
* @param rowMapper
* @return a cursor
*
* @see SQLiteDatabase#query(String, String[], String, String[], String,
* String, String, String)
*/
public <T> T queryForObject(RowMapper<T> rowMapper, String table,
String[] columns, String selection, String[] selectionArgs,
String groupBy, String having, String orderBy, String limit) {
T object = null;
final Cursor c = getDb(false).query(table, columns, selection, selectionArgs,
groupBy, having, orderBy, limit);
try {
if (c.moveToFirst()) {
object = rowMapper.mapRow(c, c.getCount());
}
} finally {
c.close();
}
return object;
}
/**
* Query for list
*
* @param <T>
* @param rowMapper
* @return list of object
*
* @see SQLiteDatabase#query(String, String[], String, String[], String,
* String, String, String)
*/
public <T> List<T> queryForList(RowMapper<T> rowMapper, String table,
String[] columns, String selection, String[] selectionArgs,
String groupBy, String having, String orderBy, String limit) {
List<T> list = new ArrayList<T>();
final Cursor c = getDb(false).query(table, columns, selection, selectionArgs,
groupBy, having, orderBy, limit);
try {
while (c.moveToNext()) {
list.add(rowMapper.mapRow(c, 1));
}
} finally {
c.close();
}
return list;
}
/**
* Get Primary Key
*
* @return
*/
public String getPrimaryKey() {
return mPrimaryKey;
}
/**
* Set Primary Key
*
* @param primaryKey
*/
public void setPrimaryKey(String primaryKey) {
this.mPrimaryKey = primaryKey;
}
/**
* Get Database Connection
*
* @param writeable
* @return
* @see SQLiteOpenHelper#getWritableDatabase();
* @see SQLiteOpenHelper#getReadableDatabase();
*/
public SQLiteDatabase getDb(boolean writeable) {
if (writeable) {
return mDatabaseOpenHelper.getWritableDatabase();
} else {
return mDatabaseOpenHelper.getReadableDatabase();
}
}
/**
* Some as Spring JDBC RowMapper
*
* @see org.springframework.jdbc.core.RowMapper
* @see com.ch_linghu.fanfoudroid.db.dao.SqliteTemplate
* @param <T>
*/
public interface RowMapper<T> {
public T mapRow(Cursor cursor, int rowNum);
}
}
| Java |
package com.ch_linghu.fanfoudroid.db2;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.ch_linghu.fanfoudroid.db2.FanContent.*;
public class FanDatabase {
private static final String TAG = FanDatabase.class.getSimpleName();
/**
* SQLite Database file name
*/
private static final String DATABASE_NAME = "fanfoudroid.db";
/**
* Database Version
*/
public static final int DATABASE_VERSION = 2;
/**
* self instance
*/
private static FanDatabase sInstance = null;
/**
* SQLiteDatabase Open Helper
*/
private DatabaseHelper mOpenHelper = null;
/**
* SQLiteOpenHelper
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
// Construct
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "Create Database.");
// TODO: create tables
createAllTables(db);
createAllIndexes(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "Upgrade Database.");
// TODO: DROP TABLE
onCreate(db);
}
}
/**
* Construct
*
* @param context
*/
private FanDatabase(Context context) {
mOpenHelper = new DatabaseHelper(context);
}
/**
* Get Database
*
* @param context
* @return
*/
public static synchronized FanDatabase getInstance(Context context) {
if (null == sInstance) {
sInstance = new FanDatabase(context);
}
return sInstance;
}
/**
* Get SQLiteDatabase Open Helper
*
* @return
*/
public SQLiteOpenHelper getSQLiteOpenHelper() {
return mOpenHelper;
}
/**
* Get Database Connection
*
* @param writeable
* @return
*/
public SQLiteDatabase getDb(boolean writeable) {
if (writeable) {
return mOpenHelper.getWritableDatabase();
} else {
return mOpenHelper.getReadableDatabase();
}
}
/**
* Close Database
*/
public void close() {
if (null != sInstance) {
mOpenHelper.close();
sInstance = null;
}
}
// Create All tables
private static void createAllTables(SQLiteDatabase db) {
db.execSQL(StatusesTable.getCreateSQL());
db.execSQL(StatusesPropertyTable.getCreateSQL());
db.execSQL(UserTable.getCreateSQL());
db.execSQL(DirectMessageTable.getCreateSQL());
db.execSQL(FollowRelationshipTable.getCreateSQL());
db.execSQL(TrendTable.getCreateSQL());
db.execSQL(SavedSearchTable.getCreateSQL());
}
private static void dropAllTables(SQLiteDatabase db) {
db.execSQL(StatusesTable.getDropSQL());
db.execSQL(StatusesPropertyTable.getDropSQL());
db.execSQL(UserTable.getDropSQL());
db.execSQL(DirectMessageTable.getDropSQL());
db.execSQL(FollowRelationshipTable.getDropSQL());
db.execSQL(TrendTable.getDropSQL());
db.execSQL(SavedSearchTable.getDropSQL());
}
private static void resetAllTables(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
dropAllTables(db);
} catch (SQLException e) {
Log.e(TAG, "resetAllTables ERROR!");
}
createAllTables(db);
}
//indexes
private static void createAllIndexes(SQLiteDatabase db) {
db.execSQL(StatusesTable.getCreateIndexSQL());
}
}
| Java |
package com.ch_linghu.fanfoudroid.db2;
import java.util.zip.CheckedOutputStream;
import android.R.color;
public abstract class FanContent {
/**
* 消息表 消息表存放消息本身
*
* @author phoenix
*
*/
public static class StatusesTable {
public static final String TABLE_NAME = "t_statuses";
public static class Columns {
public static final String ID = "_id";
public static final String STATUS_ID = "status_id";
public static final String AUTHOR_ID = "author_id";
public static final String TEXT = "text";
public static final String SOURCE = "source";
public static final String CREATED_AT = "created_at";
public static final String TRUNCATED = "truncated";
public static final String FAVORITED = "favorited";
public static final String PHOTO_URL = "photo_url";
public static final String IN_REPLY_TO_STATUS_ID = "in_reply_to_status_id";
public static final String IN_REPLY_TO_USER_ID = "in_reply_to_user_id";
public static final String IN_REPLY_TO_SCREEN_NAME = "in_reply_to_screen_name";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.ID
+ " INTEGER PRIMARY KEY, " + Columns.STATUS_ID
+ " TEXT UNIQUE NOT NULL, " + Columns.AUTHOR_ID + " TEXT, "
+ Columns.TEXT + " TEXT, " + Columns.SOURCE + " TEXT, "
+ Columns.CREATED_AT + " INT, " + Columns.TRUNCATED
+ " INT DEFAULT 0, " + Columns.FAVORITED
+ " INT DEFAULT 0, " + Columns.PHOTO_URL + " TEXT, "
+ Columns.IN_REPLY_TO_STATUS_ID + " TEXT, "
+ Columns.IN_REPLY_TO_USER_ID + " TEXT, "
+ Columns.IN_REPLY_TO_SCREEN_NAME + " TEXT " + ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.ID, Columns.STATUS_ID,
Columns.AUTHOR_ID, Columns.TEXT, Columns.SOURCE,
Columns.CREATED_AT, Columns.TRUNCATED, Columns.FAVORITED,
Columns.PHOTO_URL, Columns.IN_REPLY_TO_STATUS_ID,
Columns.IN_REPLY_TO_USER_ID,
Columns.IN_REPLY_TO_SCREEN_NAME };
}
public static String getCreateIndexSQL() {
String createIndexSQL = "CREATE INDEX " + TABLE_NAME + "_idx ON "
+ TABLE_NAME + " ( " + getIndexColumns()[1] + " );";
return createIndexSQL;
}
}
/**
* 消息属性表 每一条消息所属类别、所有者等信息 消息ID(外键) 所有者(随便看看的所有者为空)
* 消息类别(随便看看/首页(自己及自己好友)/个人(仅自己)/收藏/照片)
*
* @author phoenix
*
*/
public static class StatusesPropertyTable {
public static final String TABLE_NAME = "t_statuses_property";
public static class Columns {
public static final String ID = "_id";
public static final String STATUS_ID = "status_id";
public static final String OWNER_ID = "owner_id";
public static final String TYPE = "type";
public static final String SEQUENCE_FLAG = "sequence_flag";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.ID
+ " INTEGER PRIMARY KEY, " + Columns.STATUS_ID
+ " TEXT NOT NULL, " + Columns.OWNER_ID + " TEXT, "
+ Columns.TYPE + " INT, " + Columns.SEQUENCE_FLAG
+ " INT, " + Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.ID, Columns.STATUS_ID,
Columns.OWNER_ID, Columns.TYPE, Columns.SEQUENCE_FLAG,
Columns.LOAD_TIME };
}
}
/**
* User表 包括User的基本信息和扩展信息(每次获得最新User信息都update进User表)
* 每次更新User表时希望能更新LOAD_TIME,记录最后更新时间
*
* @author phoenix
*
*/
public static class UserTable {
public static final String TABLE_NAME = "t_user";
public static class Columns {
public static final String ID = "_id";
public static final String USER_ID = "user_id";
public static final String USER_NAME = "user_name";
public static final String SCREEN_NAME = "screen_name";
public static final String LOCATION = "location";
public static final String DESCRIPTION = "description";
public static final String URL = "url";
public static final String PROTECTED = "protected";
public static final String PROFILE_IMAGE_URL = "profile_image_url";
public static final String FOLLOWERS_COUNT = "followers_count";
public static final String FRIENDS_COUNT = "friends_count";
public static final String FAVOURITES_COUNT = "favourites_count";
public static final String STATUSES_COUNT = "statuses_count";
public static final String CREATED_AT = "created_at";
public static final String FOLLOWING = "following";
public static final String NOTIFICATIONS = "notifications";
public static final String UTC_OFFSET = "utc_offset";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.ID
+ " INTEGER PRIMARY KEY, " + Columns.USER_ID
+ " TEXT UNIQUE NOT NULL, " + Columns.USER_NAME
+ " TEXT UNIQUE NOT NULL, " + Columns.SCREEN_NAME
+ " TEXT, " + Columns.LOCATION + " TEXT, "
+ Columns.DESCRIPTION + " TEXT, " + Columns.URL + " TEXT, "
+ Columns.PROTECTED + " INT DEFAULT 0, "
+ Columns.PROFILE_IMAGE_URL + " TEXT "
+ Columns.FOLLOWERS_COUNT + " INT, "
+ Columns.FRIENDS_COUNT + " INT, "
+ Columns.FAVOURITES_COUNT + " INT, "
+ Columns.STATUSES_COUNT + " INT, " + Columns.CREATED_AT
+ " INT, " + Columns.FOLLOWING + " INT DEFAULT 0, "
+ Columns.NOTIFICATIONS + " INT DEFAULT 0, "
+ Columns.UTC_OFFSET + " TEXT, " + Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.ID, Columns.USER_ID,
Columns.USER_NAME, Columns.SCREEN_NAME, Columns.LOCATION,
Columns.DESCRIPTION, Columns.URL, Columns.PROTECTED,
Columns.PROFILE_IMAGE_URL, Columns.FOLLOWERS_COUNT,
Columns.FRIENDS_COUNT, Columns.FAVOURITES_COUNT,
Columns.STATUSES_COUNT, Columns.CREATED_AT,
Columns.FOLLOWING, Columns.NOTIFICATIONS,
Columns.UTC_OFFSET, Columns.LOAD_TIME };
}
}
/**
* 私信表 私信的基本信息
*
* @author phoenix
*
*/
public static class DirectMessageTable {
public static final String TABLE_NAME = "t_direct_message";
public static class Columns {
public static final String ID = "_id";
public static final String MSG_ID = "msg_id";
public static final String TEXT = "text";
public static final String SENDER_ID = "sender_id";
public static final String RECIPINET_ID = "recipinet_id";
public static final String CREATED_AT = "created_at";
public static final String LOAD_TIME = "load_time";
public static final String SEQUENCE_FLAG = "sequence_flag";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.ID
+ " INTEGER PRIMARY KEY, " + Columns.MSG_ID
+ " TEXT UNIQUE NOT NULL, " + Columns.TEXT + " TEXT, "
+ Columns.SENDER_ID + " TEXT, " + Columns.RECIPINET_ID
+ " TEXT, " + Columns.CREATED_AT + " INT, "
+ Columns.SEQUENCE_FLAG + " INT, " + Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.ID, Columns.MSG_ID, Columns.TEXT,
Columns.SENDER_ID, Columns.RECIPINET_ID,
Columns.CREATED_AT, Columns.SEQUENCE_FLAG,
Columns.LOAD_TIME };
}
}
/**
* Follow关系表 某个特定用户的Follow关系(User1 following User2,
* 查找关联某人好友只需限定User1或者User2)
*
* @author phoenix
*
*/
public static class FollowRelationshipTable {
public static final String TABLE_NAME = "t_follow_relationship";
public static class Columns {
public static final String USER1_ID = "user1_id";
public static final String USER2_ID = "user2_id";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.USER1_ID
+ " TEXT, " + Columns.USER2_ID + " TEXT, "
+ Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.USER1_ID, Columns.USER2_ID,
Columns.LOAD_TIME };
}
}
/**
* 热门话题表 记录每次查询得到的热词
*
* @author phoenix
*
*/
public static class TrendTable {
public static final String TABLE_NAME = "t_trend";
public static class Columns {
public static final String NAME = "name";
public static final String QUERY = "query";
public static final String URL = "url";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.NAME + " TEXT, "
+ Columns.QUERY + " TEXT, " + Columns.URL + " TEXT, "
+ Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.NAME, Columns.QUERY, Columns.URL,
Columns.LOAD_TIME };
}
}
/**
* 保存搜索表 QUERY_ID(这个ID在API删除保存搜索词时使用)
*
* @author phoenix
*
*/
public static class SavedSearchTable {
public static final String TABLE_NAME = "t_saved_search";
public static class Columns {
public static final String QUERY_ID = "query_id";
public static final String QUERY = "query";
public static final String NAME = "name";
public static final String CREATED_AT = "created_at";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.QUERY_ID
+ " INT, " + Columns.QUERY + " TEXT, " + Columns.NAME
+ " TEXT, " + Columns.CREATED_AT + " INT, "
+ Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.QUERY_ID, Columns.QUERY,
Columns.NAME, Columns.CREATED_AT, Columns.LOAD_TIME };
}
}
}
| Java |
package com.ch_linghu.fanfoudroid.db2;
import java.util.ArrayList;
import java.util.Arrays;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
/**
* Wrapper of SQliteDatabse#query, OOP style.
*
* Usage:
* ------------------------------------------------
* Query select = new Query(SQLiteDatabase);
*
* // SELECT
* query.from("tableName", new String[] { "colName" })
* .where("id = ?", 123456)
* .where("name = ?", "jack")
* .orderBy("created_at DESC")
* .limit(1);
* Cursor cursor = query.select();
*
* // DELETE
* query.from("tableName")
* .where("id = ?", 123455);
* .delete();
*
* // UPDATE
* query.setTable("tableName")
* .values(contentValues)
* .update();
*
* // INSERT
* query.into("tableName")
* .values(contentValues)
* .insert();
* ------------------------------------------------
*
* @see SQLiteDatabase#query(String, String[], String, String[], String, String, String, String)
*/
public class Query
{
private static final String TAG = "Query-Builder";
/** TEMP list for selctionArgs */
private ArrayList<String> binds = new ArrayList<String>();
private SQLiteDatabase mDb = null;
private String mTable;
private String[] mColumns;
private String mSelection = null;
private String[] mSelectionArgs = null;
private String mGroupBy = null;
private String mHaving = null;
private String mOrderBy = null;
private String mLimit = null;
private ContentValues mValues = null;
private String mNullColumnHack = null;
public Query() { }
/**
* Construct
*
* @param db
*/
public Query(SQLiteDatabase db) {
this.setDb(db);
}
/**
* Query the given table, returning a Cursor over the result set.
*
* @param db SQLitedatabase
* @return A Cursor object, which is positioned before the first entry, or NULL
*/
public Cursor select() {
if ( preCheck() ) {
buildQuery();
return mDb.query(mTable, mColumns, mSelection, mSelectionArgs,
mGroupBy, mHaving, mOrderBy, mLimit);
} else {
//throw new SelectException("Cann't build the query . " + toString());
Log.e(TAG, "Cann't build the query " + toString());
return null;
}
}
/**
* @return the number of rows affected if a whereClause is passed in, 0
* otherwise. To remove all rows and get a count pass "1" as the
* whereClause.
*/
public int delete() {
if ( preCheck() ) {
buildQuery();
return mDb.delete(mTable, mSelection, mSelectionArgs);
} else {
Log.e(TAG, "Cann't build the query " + toString());
return -1;
}
}
/**
* Set FROM
*
* @param table
* The table name to compile the query against.
* @param columns
* A list of which columns to return. Passing null will return
* all columns, which is discouraged to prevent reading data from
* storage that isn't going to be used.
* @return self
*
*/
public Query from(String table, String[] columns) {
mTable = table;
mColumns = columns;
return this;
}
/**
* @see Query#from(String table, String[] columns)
* @param table
* @return self
*/
public Query from(String table) {
return from(table, null); // all columns
}
/**
* Add WHERE
*
* @param selection
* A filter declaring which rows to return, formatted as an SQL
* WHERE clause (excluding the WHERE itself). Passing null will
* return all rows for the given table.
* @param selectionArgs
* You may include ?s in selection, which will be replaced by the
* values from selectionArgs, in order that they appear in the
* selection. The values will be bound as Strings.
* @return self
*/
public Query where(String selection, String[] selectionArgs) {
addSelection(selection);
binds.addAll(Arrays.asList(selectionArgs));
return this;
}
/**
* @see Query#where(String selection, String[] selectionArgs)
*/
public Query where(String selection, String selectionArg) {
addSelection(selection);
binds.add(selectionArg);
return this;
}
/**
* @see Query#where(String selection, String[] selectionArgs)
*/
public Query where(String selection) {
addSelection(selection);
return this;
}
/**
* add selection part
*
* @param selection
*/
private void addSelection(String selection) {
if (null == mSelection) {
mSelection = selection;
} else {
mSelection += " AND " + selection;
}
}
/**
* set HAVING
*
* @param having
* A filter declare which row groups to include in the cursor, if
* row grouping is being used, formatted as an SQL HAVING clause
* (excluding the HAVING itself). Passing null will cause all row
* groups to be included, and is required when row grouping is
* not being used.
* @return self
*/
public Query having(String having) {
this.mHaving = having;
return this;
}
/**
* Set GROUP BY
*
* @param groupBy
* A filter declaring how to group rows, formatted as an SQL
* GROUP BY clause (excluding the GROUP BY itself). Passing null
* will cause the rows to not be grouped.
* @return self
*/
public Query groupBy(String groupBy) {
this.mGroupBy = groupBy;
return this;
}
/**
* Set ORDER BY
*
* @param orderBy
* How to order the rows, formatted as an SQL ORDER BY clause
* (excluding the ORDER BY itself). Passing null will use the
* default sort order, which may be unordered.
* @return self
*/
public Query orderBy(String orderBy) {
this.mOrderBy = orderBy;
return this;
}
/**
* @param limit
* Limits the number of rows returned by the query, formatted as
* LIMIT clause. Passing null denotes no LIMIT clause.
* @return self
*/
public Query limit(String limit) {
this.mLimit = limit;
return this;
}
/**
* @see Query#limit(String limit)
*/
public Query limit(int limit) {
return limit(limit + "");
}
/**
* Merge selectionArgs
*/
private void buildQuery() {
mSelectionArgs = new String[binds.size()];
binds.toArray(mSelectionArgs);
Log.v(TAG, toString());
}
private boolean preCheck() {
return (mTable != null && mDb != null);
}
// For Insert
/**
* set insert table
*
* @param table table name
* @return self
*/
public Query into(String table) {
return setTable(table);
}
/**
* Set new values
*
* @param values new values
* @return self
*/
public Query values(ContentValues values) {
mValues = values;
return this;
}
/**
* Insert a row
*
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long insert() {
return mDb.insert(mTable, mNullColumnHack, mValues);
}
// For update
/**
* Set target table
*
* @param table table name
* @return self
*/
public Query setTable(String table) {
mTable = table;
return this;
}
/**
* Update a row
*
* @return the number of rows affected, or -1 if an error occurred
*/
public int update() {
if ( preCheck() ) {
buildQuery();
return mDb.update(mTable, mValues, mSelection, mSelectionArgs);
} else {
Log.e(TAG, "Cann't build the query " + toString());
return -1;
}
}
/**
* Set back-end database
* @param db
*/
public void setDb(SQLiteDatabase db) {
if (null == this.mDb) {
this.mDb = db;
}
}
@Override
public String toString() {
return "Query [table=" + mTable + ", columns="
+ Arrays.toString(mColumns) + ", selection=" + mSelection
+ ", selectionArgs=" + Arrays.toString(mSelectionArgs)
+ ", groupBy=" + mGroupBy + ", having=" + mHaving + ", orderBy="
+ mOrderBy + "]";
}
/** for debug */
public ContentValues getContentValues() {
return mValues;
}
}
| Java |
package com.ch_linghu.fanfoudroid.http;
import java.util.HashMap;
import java.util.Map;
public class HTMLEntity {
public static String escape(String original) {
StringBuffer buf = new StringBuffer(original);
escape(buf);
return buf.toString();
}
public static void escape(StringBuffer original) {
int index = 0;
String escaped;
while (index < original.length()) {
escaped = entityEscapeMap.get(original.substring(index, index + 1));
if (null != escaped) {
original.replace(index, index + 1, escaped);
index += escaped.length();
} else {
index++;
}
}
}
public static String unescape(String original) {
StringBuffer buf = new StringBuffer(original);
unescape(buf);
return buf.toString();
}
public static void unescape(StringBuffer original) {
int index = 0;
int semicolonIndex = 0;
String escaped;
String entity;
while (index < original.length()) {
index = original.indexOf("&", index);
if (-1 == index) {
break;
}
semicolonIndex = original.indexOf(";", index);
if (-1 != semicolonIndex && 10 > (semicolonIndex - index)) {
escaped = original.substring(index, semicolonIndex + 1);
entity = escapeEntityMap.get(escaped);
if (null != entity) {
original.replace(index, semicolonIndex + 1, entity);
}
index++;
} else {
break;
}
}
}
private static Map<String, String> entityEscapeMap = new HashMap<String, String>();
private static Map<String, String> escapeEntityMap = new HashMap<String, String>();
static {
String[][] entities =
{{" ", " "/* no-break space = non-breaking space */, "\u00A0"}
, {"¡", "¡"/* inverted exclamation mark */, "\u00A1"}
, {"¢", "¢"/* cent sign */, "\u00A2"}
, {"£", "£"/* pound sign */, "\u00A3"}
, {"¤", "¤"/* currency sign */, "\u00A4"}
, {"¥", "¥"/* yen sign = yuan sign */, "\u00A5"}
, {"¦", "¦"/* broken bar = broken vertical bar */, "\u00A6"}
, {"§", "§"/* section sign */, "\u00A7"}
, {"¨", "¨"/* diaeresis = spacing diaeresis */, "\u00A8"}
, {"©", "©"/* copyright sign */, "\u00A9"}
, {"ª", "ª"/* feminine ordinal indicator */, "\u00AA"}
, {"«", "«"/* left-pointing double angle quotation mark = left pointing guillemet */, "\u00AB"}
, {"¬", "¬"/* not sign = discretionary hyphen */, "\u00AC"}
, {"­", "­"/* soft hyphen = discretionary hyphen */, "\u00AD"}
, {"®", "®"/* registered sign = registered trade mark sign */, "\u00AE"}
, {"¯", "¯"/* macron = spacing macron = overline = APL overbar */, "\u00AF"}
, {"°", "°"/* degree sign */, "\u00B0"}
, {"±", "±"/* plus-minus sign = plus-or-minus sign */, "\u00B1"}
, {"²", "²"/* superscript two = superscript digit two = squared */, "\u00B2"}
, {"³", "³"/* superscript three = superscript digit three = cubed */, "\u00B3"}
, {"´", "´"/* acute accent = spacing acute */, "\u00B4"}
, {"µ", "µ"/* micro sign */, "\u00B5"}
, {"¶", "¶"/* pilcrow sign = paragraph sign */, "\u00B6"}
, {"·", "·"/* middle dot = Georgian comma = Greek middle dot */, "\u00B7"}
, {"¸", "¸"/* cedilla = spacing cedilla */, "\u00B8"}
, {"¹", "¹"/* superscript one = superscript digit one */, "\u00B9"}
, {"º", "º"/* masculine ordinal indicator */, "\u00BA"}
, {"»", "»"/* right-pointing double angle quotation mark = right pointing guillemet */, "\u00BB"}
, {"¼", "¼"/* vulgar fraction one quarter = fraction one quarter */, "\u00BC"}
, {"½", "½"/* vulgar fraction one half = fraction one half */, "\u00BD"}
, {"¾", "¾"/* vulgar fraction three quarters = fraction three quarters */, "\u00BE"}
, {"¿", "¿"/* inverted question mark = turned question mark */, "\u00BF"}
, {"À", "À"/* latin capital letter A with grave = latin capital letter A grave */, "\u00C0"}
, {"Á", "Á"/* latin capital letter A with acute */, "\u00C1"}
, {"Â", "Â"/* latin capital letter A with circumflex */, "\u00C2"}
, {"Ã", "Ã"/* latin capital letter A with tilde */, "\u00C3"}
, {"Ä", "Ä"/* latin capital letter A with diaeresis */, "\u00C4"}
, {"Å", "Å"/* latin capital letter A with ring above = latin capital letter A ring */, "\u00C5"}
, {"Æ", "Æ"/* latin capital letter AE = latin capital ligature AE */, "\u00C6"}
, {"Ç", "Ç"/* latin capital letter C with cedilla */, "\u00C7"}
, {"È", "È"/* latin capital letter E with grave */, "\u00C8"}
, {"É", "É"/* latin capital letter E with acute */, "\u00C9"}
, {"Ê", "Ê"/* latin capital letter E with circumflex */, "\u00CA"}
, {"Ë", "Ë"/* latin capital letter E with diaeresis */, "\u00CB"}
, {"Ì", "Ì"/* latin capital letter I with grave */, "\u00CC"}
, {"Í", "Í"/* latin capital letter I with acute */, "\u00CD"}
, {"Î", "Î"/* latin capital letter I with circumflex */, "\u00CE"}
, {"Ï", "Ï"/* latin capital letter I with diaeresis */, "\u00CF"}
, {"Ð", "Ð"/* latin capital letter ETH */, "\u00D0"}
, {"Ñ", "Ñ"/* latin capital letter N with tilde */, "\u00D1"}
, {"Ò", "Ò"/* latin capital letter O with grave */, "\u00D2"}
, {"Ó", "Ó"/* latin capital letter O with acute */, "\u00D3"}
, {"Ô", "Ô"/* latin capital letter O with circumflex */, "\u00D4"}
, {"Õ", "Õ"/* latin capital letter O with tilde */, "\u00D5"}
, {"Ö", "Ö"/* latin capital letter O with diaeresis */, "\u00D6"}
, {"×", "×"/* multiplication sign */, "\u00D7"}
, {"Ø", "Ø"/* latin capital letter O with stroke = latin capital letter O slash */, "\u00D8"}
, {"Ù", "Ù"/* latin capital letter U with grave */, "\u00D9"}
, {"Ú", "Ú"/* latin capital letter U with acute */, "\u00DA"}
, {"Û", "Û"/* latin capital letter U with circumflex */, "\u00DB"}
, {"Ü", "Ü"/* latin capital letter U with diaeresis */, "\u00DC"}
, {"Ý", "Ý"/* latin capital letter Y with acute */, "\u00DD"}
, {"Þ", "Þ"/* latin capital letter THORN */, "\u00DE"}
, {"ß", "ß"/* latin small letter sharp s = ess-zed */, "\u00DF"}
, {"à", "à"/* latin small letter a with grave = latin small letter a grave */, "\u00E0"}
, {"á", "á"/* latin small letter a with acute */, "\u00E1"}
, {"â", "â"/* latin small letter a with circumflex */, "\u00E2"}
, {"ã", "ã"/* latin small letter a with tilde */, "\u00E3"}
, {"ä", "ä"/* latin small letter a with diaeresis */, "\u00E4"}
, {"å", "å"/* latin small letter a with ring above = latin small letter a ring */, "\u00E5"}
, {"æ", "æ"/* latin small letter ae = latin small ligature ae */, "\u00E6"}
, {"ç", "ç"/* latin small letter c with cedilla */, "\u00E7"}
, {"è", "è"/* latin small letter e with grave */, "\u00E8"}
, {"é", "é"/* latin small letter e with acute */, "\u00E9"}
, {"ê", "ê"/* latin small letter e with circumflex */, "\u00EA"}
, {"ë", "ë"/* latin small letter e with diaeresis */, "\u00EB"}
, {"ì", "ì"/* latin small letter i with grave */, "\u00EC"}
, {"í", "í"/* latin small letter i with acute */, "\u00ED"}
, {"î", "î"/* latin small letter i with circumflex */, "\u00EE"}
, {"ï", "ï"/* latin small letter i with diaeresis */, "\u00EF"}
, {"ð", "ð"/* latin small letter eth */, "\u00F0"}
, {"ñ", "ñ"/* latin small letter n with tilde */, "\u00F1"}
, {"ò", "ò"/* latin small letter o with grave */, "\u00F2"}
, {"ó", "ó"/* latin small letter o with acute */, "\u00F3"}
, {"ô", "ô"/* latin small letter o with circumflex */, "\u00F4"}
, {"õ", "õ"/* latin small letter o with tilde */, "\u00F5"}
, {"ö", "ö"/* latin small letter o with diaeresis */, "\u00F6"}
, {"÷", "÷"/* division sign */, "\u00F7"}
, {"ø", "ø"/* latin small letter o with stroke = latin small letter o slash */, "\u00F8"}
, {"ù", "ù"/* latin small letter u with grave */, "\u00F9"}
, {"ú", "ú"/* latin small letter u with acute */, "\u00FA"}
, {"û", "û"/* latin small letter u with circumflex */, "\u00FB"}
, {"ü", "ü"/* latin small letter u with diaeresis */, "\u00FC"}
, {"ý", "ý"/* latin small letter y with acute */, "\u00FD"}
, {"þ", "þ"/* latin small letter thorn with */, "\u00FE"}
, {"ÿ", "ÿ"/* latin small letter y with diaeresis */, "\u00FF"}
, {"ƒ", "ƒ"/* latin small f with hook = function = florin */, "\u0192"}
/* Greek */
, {"Α", "Α"/* greek capital letter alpha */, "\u0391"}
, {"Β", "Β"/* greek capital letter beta */, "\u0392"}
, {"Γ", "Γ"/* greek capital letter gamma */, "\u0393"}
, {"Δ", "Δ"/* greek capital letter delta */, "\u0394"}
, {"Ε", "Ε"/* greek capital letter epsilon */, "\u0395"}
, {"Ζ", "Ζ"/* greek capital letter zeta */, "\u0396"}
, {"Η", "Η"/* greek capital letter eta */, "\u0397"}
, {"Θ", "Θ"/* greek capital letter theta */, "\u0398"}
, {"Ι", "Ι"/* greek capital letter iota */, "\u0399"}
, {"Κ", "Κ"/* greek capital letter kappa */, "\u039A"}
, {"Λ", "Λ"/* greek capital letter lambda */, "\u039B"}
, {"Μ", "Μ"/* greek capital letter mu */, "\u039C"}
, {"Ν", "Ν"/* greek capital letter nu */, "\u039D"}
, {"Ξ", "Ξ"/* greek capital letter xi */, "\u039E"}
, {"Ο", "Ο"/* greek capital letter omicron */, "\u039F"}
, {"Π", "Π"/* greek capital letter pi */, "\u03A0"}
, {"Ρ", "Ρ"/* greek capital letter rho */, "\u03A1"}
/* there is no Sigmaf and no \u03A2 */
, {"Σ", "Σ"/* greek capital letter sigma */, "\u03A3"}
, {"Τ", "Τ"/* greek capital letter tau */, "\u03A4"}
, {"Υ", "Υ"/* greek capital letter upsilon */, "\u03A5"}
, {"Φ", "Φ"/* greek capital letter phi */, "\u03A6"}
, {"Χ", "Χ"/* greek capital letter chi */, "\u03A7"}
, {"Ψ", "Ψ"/* greek capital letter psi */, "\u03A8"}
, {"Ω", "Ω"/* greek capital letter omega */, "\u03A9"}
, {"α", "α"/* greek small letter alpha */, "\u03B1"}
, {"β", "β"/* greek small letter beta */, "\u03B2"}
, {"γ", "γ"/* greek small letter gamma */, "\u03B3"}
, {"δ", "δ"/* greek small letter delta */, "\u03B4"}
, {"ε", "ε"/* greek small letter epsilon */, "\u03B5"}
, {"ζ", "ζ"/* greek small letter zeta */, "\u03B6"}
, {"η", "η"/* greek small letter eta */, "\u03B7"}
, {"θ", "θ"/* greek small letter theta */, "\u03B8"}
, {"ι", "ι"/* greek small letter iota */, "\u03B9"}
, {"κ", "κ"/* greek small letter kappa */, "\u03BA"}
, {"λ", "λ"/* greek small letter lambda */, "\u03BB"}
, {"μ", "μ"/* greek small letter mu */, "\u03BC"}
, {"ν", "ν"/* greek small letter nu */, "\u03BD"}
, {"ξ", "ξ"/* greek small letter xi */, "\u03BE"}
, {"ο", "ο"/* greek small letter omicron */, "\u03BF"}
, {"π", "π"/* greek small letter pi */, "\u03C0"}
, {"ρ", "ρ"/* greek small letter rho */, "\u03C1"}
, {"ς", "ς"/* greek small letter final sigma */, "\u03C2"}
, {"σ", "σ"/* greek small letter sigma */, "\u03C3"}
, {"τ", "τ"/* greek small letter tau */, "\u03C4"}
, {"υ", "υ"/* greek small letter upsilon */, "\u03C5"}
, {"φ", "φ"/* greek small letter phi */, "\u03C6"}
, {"χ", "χ"/* greek small letter chi */, "\u03C7"}
, {"ψ", "ψ"/* greek small letter psi */, "\u03C8"}
, {"ω", "ω"/* greek small letter omega */, "\u03C9"}
, {"ϑ", "ϑ"/* greek small letter theta symbol */, "\u03D1"}
, {"ϒ", "ϒ"/* greek upsilon with hook symbol */, "\u03D2"}
, {"ϖ", "ϖ"/* greek pi symbol */, "\u03D6"}
/* General Punctuation */
, {"•", "•"/* bullet = black small circle */, "\u2022"}
/* bullet is NOT the same as bullet operator ,"\u2219*/
, {"…", "…"/* horizontal ellipsis = three dot leader */, "\u2026"}
, {"′", "′"/* prime = minutes = feet */, "\u2032"}
, {"″", "″"/* double prime = seconds = inches */, "\u2033"}
, {"‾", "‾"/* overline = spacing overscore */, "\u203E"}
, {"⁄", "⁄"/* fraction slash */, "\u2044"}
/* Letterlike Symbols */
, {"℘", "℘"/* script capital P = power set = Weierstrass p */, "\u2118"}
, {"ℑ", "ℑ"/* blackletter capital I = imaginary part */, "\u2111"}
, {"ℜ", "ℜ"/* blackletter capital R = real part symbol */, "\u211C"}
, {"™", "™"/* trade mark sign */, "\u2122"}
, {"ℵ", "ℵ"/* alef symbol = first transfinite cardinal */, "\u2135"}
/* alef symbol is NOT the same as hebrew letter alef ,"\u05D0"}*/
/* Arrows */
, {"←", "←"/* leftwards arrow */, "\u2190"}
, {"↑", "↑"/* upwards arrow */, "\u2191"}
, {"→", "→"/* rightwards arrow */, "\u2192"}
, {"↓", "↓"/* downwards arrow */, "\u2193"}
, {"↔", "↔"/* left right arrow */, "\u2194"}
, {"↵", "↵"/* downwards arrow with corner leftwards = carriage return */, "\u21B5"}
, {"⇐", "⇐"/* leftwards double arrow */, "\u21D0"}
/* Unicode does not say that lArr is the same as the 'is implied by' arrow but also does not have any other character for that function. So ? lArr can be used for 'is implied by' as ISOtech suggests */
, {"⇑", "⇑"/* upwards double arrow */, "\u21D1"}
, {"⇒", "⇒"/* rightwards double arrow */, "\u21D2"}
/* Unicode does not say this is the 'implies' character but does not have another character with this function so ? rArr can be used for 'implies' as ISOtech suggests */
, {"⇓", "⇓"/* downwards double arrow */, "\u21D3"}
, {"⇔", "⇔"/* left right double arrow */, "\u21D4"}
/* Mathematical Operators */
, {"∀", "∀"/* for all */, "\u2200"}
, {"∂", "∂"/* partial differential */, "\u2202"}
, {"∃", "∃"/* there exists */, "\u2203"}
, {"∅", "∅"/* empty set = null set = diameter */, "\u2205"}
, {"∇", "∇"/* nabla = backward difference */, "\u2207"}
, {"∈", "∈"/* element of */, "\u2208"}
, {"∉", "∉"/* not an element of */, "\u2209"}
, {"∋", "∋"/* contains as member */, "\u220B"}
/* should there be a more memorable name than 'ni'? */
, {"∏", "∏"/* n-ary product = product sign */, "\u220F"}
/* prod is NOT the same character as ,"\u03A0"}*/
, {"∑", "∑"/* n-ary sumation */, "\u2211"}
/* sum is NOT the same character as ,"\u03A3"}*/
, {"−", "−"/* minus sign */, "\u2212"}
, {"∗", "∗"/* asterisk operator */, "\u2217"}
, {"√", "√"/* square root = radical sign */, "\u221A"}
, {"∝", "∝"/* proportional to */, "\u221D"}
, {"∞", "∞"/* infinity */, "\u221E"}
, {"∠", "∠"/* angle */, "\u2220"}
, {"∧", "∧"/* logical and = wedge */, "\u2227"}
, {"∨", "∨"/* logical or = vee */, "\u2228"}
, {"∩", "∩"/* intersection = cap */, "\u2229"}
, {"∪", "∪"/* union = cup */, "\u222A"}
, {"∫", "∫"/* integral */, "\u222B"}
, {"∴", "∴"/* therefore */, "\u2234"}
, {"∼", "∼"/* tilde operator = varies with = similar to */, "\u223C"}
/* tilde operator is NOT the same character as the tilde ,"\u007E"}*/
, {"≅", "≅"/* approximately equal to */, "\u2245"}
, {"≈", "≈"/* almost equal to = asymptotic to */, "\u2248"}
, {"≠", "≠"/* not equal to */, "\u2260"}
, {"≡", "≡"/* identical to */, "\u2261"}
, {"≤", "≤"/* less-than or equal to */, "\u2264"}
, {"≥", "≥"/* greater-than or equal to */, "\u2265"}
, {"⊂", "⊂"/* subset of */, "\u2282"}
, {"⊃", "⊃"/* superset of */, "\u2283"}
/* note that nsup 'not a superset of ,"\u2283"}*/
, {"⊆", "⊆"/* subset of or equal to */, "\u2286"}
, {"⊇", "⊇"/* superset of or equal to */, "\u2287"}
, {"⊕", "⊕"/* circled plus = direct sum */, "\u2295"}
, {"⊗", "⊗"/* circled times = vector product */, "\u2297"}
, {"⊥", "⊥"/* up tack = orthogonal to = perpendicular */, "\u22A5"}
, {"⋅", "⋅"/* dot operator */, "\u22C5"}
/* dot operator is NOT the same character as ,"\u00B7"}
/* Miscellaneous Technical */
, {"⌈", "⌈"/* left ceiling = apl upstile */, "\u2308"}
, {"⌉", "⌉"/* right ceiling */, "\u2309"}
, {"⌊", "⌊"/* left floor = apl downstile */, "\u230A"}
, {"⌋", "⌋"/* right floor */, "\u230B"}
, {"⟨", "〈"/* left-pointing angle bracket = bra */, "\u2329"}
/* lang is NOT the same character as ,"\u003C"}*/
, {"⟩", "〉"/* right-pointing angle bracket = ket */, "\u232A"}
/* rang is NOT the same character as ,"\u003E"}*/
/* Geometric Shapes */
, {"◊", "◊"/* lozenge */, "\u25CA"}
/* Miscellaneous Symbols */
, {"♠", "♠"/* black spade suit */, "\u2660"}
/* black here seems to mean filled as opposed to hollow */
, {"♣", "♣"/* black club suit = shamrock */, "\u2663"}
, {"♥", "♥"/* black heart suit = valentine */, "\u2665"}
, {"♦", "♦"/* black diamond suit */, "\u2666"}
, {""", """ /* quotation mark = APL quote */, "\""}
, {"&", "&" /* ampersand */, "\u0026"}
, {"<", "<" /* less-than sign */, "\u003C"}
, {">", ">" /* greater-than sign */, "\u003E"}
/* Latin Extended-A */
, {"Œ", "Œ" /* latin capital ligature OE */, "\u0152"}
, {"œ", "œ" /* latin small ligature oe */, "\u0153"}
/* ligature is a misnomer this is a separate character in some languages */
, {"Š", "Š" /* latin capital letter S with caron */, "\u0160"}
, {"š", "š" /* latin small letter s with caron */, "\u0161"}
, {"Ÿ", "Ÿ" /* latin capital letter Y with diaeresis */, "\u0178"}
/* Spacing Modifier Letters */
, {"ˆ", "ˆ" /* modifier letter circumflex accent */, "\u02C6"}
, {"˜", "˜" /* small tilde */, "\u02DC"}
/* General Punctuation */
, {" ", " "/* en space */, "\u2002"}
, {" ", " "/* em space */, "\u2003"}
, {" ", " "/* thin space */, "\u2009"}
, {"‌", "‌"/* zero width non-joiner */, "\u200C"}
, {"‍", "‍"/* zero width joiner */, "\u200D"}
, {"‎", "‎"/* left-to-right mark */, "\u200E"}
, {"‏", "‏"/* right-to-left mark */, "\u200F"}
, {"–", "–"/* en dash */, "\u2013"}
, {"—", "—"/* em dash */, "\u2014"}
, {"‘", "‘"/* left single quotation mark */, "\u2018"}
, {"’", "’"/* right single quotation mark */, "\u2019"}
, {"‚", "‚"/* single low-9 quotation mark */, "\u201A"}
, {"“", "“"/* left double quotation mark */, "\u201C"}
, {"”", "”"/* right double quotation mark */, "\u201D"}
, {"„", "„"/* double low-9 quotation mark */, "\u201E"}
, {"†", "†"/* dagger */, "\u2020"}
, {"‡", "‡"/* double dagger */, "\u2021"}
, {"‰", "‰"/* per mille sign */, "\u2030"}
, {"‹", "‹"/* single left-pointing angle quotation mark */, "\u2039"}
/* lsaquo is proposed but not yet ISO standardized */
, {"›", "›"/* single right-pointing angle quotation mark */, "\u203A"}
/* rsaquo is proposed but not yet ISO standardized */
, {"€", "€" /* euro sign */, "\u20AC"}};
for (String[] entity : entities) {
entityEscapeMap.put(entity[2], entity[0]);
escapeEntityMap.put(entity[0], entity[2]);
escapeEntityMap.put(entity[1], entity[2]);
}
}
}
| Java |
package com.ch_linghu.fanfoudroid.http;
/**
* HTTP StatusCode is not 200
*/
public class HttpException extends Exception {
private int statusCode = -1;
public HttpException(String msg) {
super(msg);
}
public HttpException(Exception cause) {
super(cause);
}
public HttpException(String msg, int statusCode) {
super(msg);
this.statusCode = statusCode;
}
public HttpException(String msg, Exception cause) {
super(msg, cause);
}
public HttpException(String msg, Exception cause, int statusCode) {
super(msg, cause);
this.statusCode = statusCode;
}
public int getStatusCode() {
return this.statusCode;
}
}
| Java |
package com.ch_linghu.fanfoudroid.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.CharArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import android.util.Log;
import com.ch_linghu.fanfoudroid.util.DebugTimer;
public class Response {
private final HttpResponse mResponse;
private boolean mStreamConsumed = false;
public Response(HttpResponse res) {
mResponse = res;
}
/**
* Convert Response to inputStream
*
* @return InputStream or null
* @throws ResponseException
*/
public InputStream asStream() throws ResponseException {
try {
final HttpEntity entity = mResponse.getEntity();
if (entity != null) {
return entity.getContent();
}
} catch (IllegalStateException e) {
throw new ResponseException(e.getMessage(), e);
} catch (IOException e) {
throw new ResponseException(e.getMessage(), e);
}
return null;
}
/**
* @deprecated use entity.getContent();
* @param entity
* @return
* @throws ResponseException
*/
private InputStream asStream(HttpEntity entity) throws ResponseException {
if (null == entity) {
return null;
}
InputStream is = null;
try {
is = entity.getContent();
} catch (IllegalStateException e) {
throw new ResponseException(e.getMessage(), e);
} catch (IOException e) {
throw new ResponseException(e.getMessage(), e);
}
//mResponse = null;
return is;
}
/**
* Convert Response to Context String
*
* @return response context string or null
* @throws ResponseException
*/
public String asString() throws ResponseException {
try {
return entityToString(mResponse.getEntity());
} catch (IOException e) {
throw new ResponseException(e.getMessage(), e);
}
}
/**
* EntityUtils.toString(entity, "UTF-8");
*
* @param entity
* @return
* @throws IOException
* @throws ResponseException
*/
private String entityToString(final HttpEntity entity) throws IOException, ResponseException {
DebugTimer.betweenStart("AS STRING");
if (null == entity) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
//InputStream instream = asStream(entity);
if (instream == null) {
return "";
}
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
}
int i = (int) entity.getContentLength();
if (i < 0) {
i = 4096;
}
Log.i("LDS", i + " content length");
Reader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
CharArrayBuffer buffer = new CharArrayBuffer(i);
try {
char[] tmp = new char[1024];
int l;
while ((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
} finally {
reader.close();
}
DebugTimer.betweenEnd("AS STRING");
return buffer.toString();
}
/**
* @deprecated use entityToString()
* @param in
* @return
* @throws ResponseException
*/
private String inputStreamToString(final InputStream in) throws IOException {
if (null == in) {
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuffer buf = new StringBuffer();
try {
char[] buffer = new char[1024];
while ((reader.read(buffer)) != -1) {
buf.append(buffer);
}
return buf.toString();
} finally {
if (reader != null) {
reader.close();
setStreamConsumed(true);
}
}
}
public JSONObject asJSONObject() throws ResponseException {
try {
return new JSONObject(asString());
} catch (JSONException jsone) {
throw new ResponseException(jsone.getMessage() + ":"
+ asString(), jsone);
}
}
public JSONArray asJSONArray() throws ResponseException {
try {
return new JSONArray(asString());
} catch (Exception jsone) {
throw new ResponseException(jsone.getMessage(), jsone);
}
}
private void setStreamConsumed(boolean mStreamConsumed) {
this.mStreamConsumed = mStreamConsumed;
}
public boolean isStreamConsumed() {
return mStreamConsumed;
}
/**
* @deprecated
* @return
*/
public Document asDocument() {
// TODO Auto-generated method stub
return null;
}
private static Pattern escaped = Pattern.compile("&#([0-9]{3,5});");
/**
* Unescape UTF-8 escaped characters to string.
* @author pengjianq...@gmail.com
*
* @param original The string to be unescaped.
* @return The unescaped string
*/
public static String unescape(String original) {
Matcher mm = escaped.matcher(original);
StringBuffer unescaped = new StringBuffer();
while (mm.find()) {
mm.appendReplacement(unescaped, Character.toString(
(char) Integer.parseInt(mm.group(1), 10)));
}
mm.appendTail(unescaped);
return unescaped.toString();
}
}
| Java |
package com.ch_linghu.fanfoudroid.http;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpVersion;
import org.apache.http.NoHttpResponseException;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.fanfou.Configuration;
import com.ch_linghu.fanfoudroid.fanfou.RefuseError;
import com.ch_linghu.fanfoudroid.util.DebugTimer;
/**
* Wrap of org.apache.http.impl.client.DefaultHttpClient
*
* @author lds
*
*/
public class HttpClient {
private static final String TAG = "HttpClient";
private final static boolean DEBUG = Configuration.getDebug();
/** OK: Success! */
public static final int OK = 200;
/** Not Modified: There was no new data to return. */
public static final int NOT_MODIFIED = 304;
/** Bad Request: The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting. */
public static final int BAD_REQUEST = 400;
/** Not Authorized: Authentication credentials were missing or incorrect. */
public static final int NOT_AUTHORIZED = 401;
/** Forbidden: The request is understood, but it has been refused. An accompanying error message will explain why. */
public static final int FORBIDDEN = 403;
/** Not Found: The URI requested is invalid or the resource requested, such as a user, does not exists. */
public static final int NOT_FOUND = 404;
/** Not Acceptable: Returned by the Search API when an invalid format is specified in the request. */
public static final int NOT_ACCEPTABLE = 406;
/** Internal Server Error: Something is broken. Please post to the group so the Weibo team can investigate. */
public static final int INTERNAL_SERVER_ERROR = 500;
/** Bad Gateway: Weibo is down or being upgraded. */
public static final int BAD_GATEWAY = 502;
/** Service Unavailable: The Weibo servers are up, but overloaded with requests. Try again later. The search and trend methods use this to indicate when you are being rate limited. */
public static final int SERVICE_UNAVAILABLE = 503;
private static final int CONNECTION_TIMEOUT_MS = 30 * 1000;
private static final int SOCKET_TIMEOUT_MS = 30 * 1000;
public static final int RETRIEVE_LIMIT = 20;
public static final int RETRIED_TIME = 3;
private static final String SERVER_HOST = "api.fanfou.com";
private DefaultHttpClient mClient;
private AuthScope mAuthScope;
private BasicHttpContext localcontext;
private String mUserId;
private String mPassword;
private static boolean isAuthenticationEnabled = false;
public HttpClient() {
prepareHttpClient();
}
/**
* @param user_id auth user
* @param password auth password
*/
public HttpClient(String user_id, String password) {
prepareHttpClient();
setCredentials(user_id, password);
}
/**
* Empty the credentials
*/
public void reset() {
setCredentials("", "");
}
/**
* @return authed user id
*/
public String getUserId() {
return mUserId;
}
/**
* @return authed user password
*/
public String getPassword() {
return mPassword;
}
/**
* @param hostname the hostname (IP or DNS name)
* @param port the port number. -1 indicates the scheme default port.
* @param scheme the name of the scheme. null indicates the default scheme
*/
public void setProxy(String host, int port, String scheme) {
HttpHost proxy = new HttpHost(host, port, scheme);
mClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
public void removeProxy() {
mClient.getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY);
}
private void enableDebug() {
Log.d(TAG, "enable apache.http debug");
java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.FINEST);
java.util.logging.Logger.getLogger("org.apache.http.wire").setLevel(java.util.logging.Level.FINER);
java.util.logging.Logger.getLogger("org.apache.http.headers").setLevel(java.util.logging.Level.OFF);
/*
System.setProperty("log.tag.org.apache.http", "VERBOSE");
System.setProperty("log.tag.org.apache.http.wire", "VERBOSE");
System.setProperty("log.tag.org.apache.http.headers", "VERBOSE");
在这里使用System.setProperty设置不会生效, 原因不明, 必须在终端上输入以下命令方能开启http调试信息:
> adb shell setprop log.tag.org.apache.http VERBOSE
> adb shell setprop log.tag.org.apache.http.wire VERBOSE
> adb shell setprop log.tag.org.apache.http.headers VERBOSE
*/
}
/**
* Setup DefaultHttpClient
*
* Use ThreadSafeClientConnManager.
*
*/
private void prepareHttpClient() {
if (DEBUG) {
enableDebug();
}
// Create and initialize HTTP parameters
HttpParams params = new BasicHttpParams();
ConnManagerParams.setMaxTotalConnections(params, 10);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
// Create and initialize scheme registry
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", SSLSocketFactory
.getSocketFactory(), 443));
// Create an HttpClient with the ThreadSafeClientConnManager.
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params,
schemeRegistry);
mClient = new DefaultHttpClient(cm, params);
// Setup BasicAuth
BasicScheme basicScheme = new BasicScheme();
mAuthScope = new AuthScope(SERVER_HOST, AuthScope.ANY_PORT);
// mClient.setAuthSchemes(authRegistry);
mClient.setCredentialsProvider(new BasicCredentialsProvider());
// Generate BASIC scheme object and stick it to the local
// execution context
localcontext = new BasicHttpContext();
localcontext.setAttribute("preemptive-auth", basicScheme);
// first request interceptor
mClient.addRequestInterceptor(preemptiveAuth, 0);
// Support GZIP
mClient.addResponseInterceptor(gzipResponseIntercepter);
// TODO: need to release this connection in httpRequest()
// cm.releaseConnection(conn, validDuration, timeUnit);
//httpclient.getConnectionManager().shutdown();
}
/**
* HttpRequestInterceptor for DefaultHttpClient
*/
private static HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
@Override
public void process(final HttpRequest request, final HttpContext context) {
AuthState authState = (AuthState) context
.getAttribute(ClientContext.TARGET_AUTH_STATE);
CredentialsProvider credsProvider = (CredentialsProvider) context
.getAttribute(ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context
.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (authState.getAuthScheme() == null) {
AuthScope authScope = new AuthScope(targetHost.getHostName(),
targetHost.getPort());
Credentials creds = credsProvider.getCredentials(authScope);
if (creds != null) {
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(creds);
}
}
}
};
private static HttpResponseInterceptor gzipResponseIntercepter =
new HttpResponseInterceptor() {
@Override
public void process(HttpResponse response, HttpContext context)
throws org.apache.http.HttpException, IOException {
HttpEntity entity = response.getEntity();
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
HeaderElement[] codecs = ceheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
response.setEntity(
new GzipDecompressingEntity(response.getEntity()));
return;
}
}
}
}
};
static class GzipDecompressingEntity extends HttpEntityWrapper {
public GzipDecompressingEntity(final HttpEntity entity) {
super(entity);
}
@Override
public InputStream getContent()
throws IOException, IllegalStateException {
// the wrapped entity's getContent() decides about repeatability
InputStream wrappedin = wrappedEntity.getContent();
return new GZIPInputStream(wrappedin);
}
@Override
public long getContentLength() {
// length of ungzipped content is not known
return -1;
}
}
/**
* Setup Credentials for HTTP Basic Auth
*
* @param username
* @param password
*/
public void setCredentials(String username, String password) {
mUserId = username;
mPassword = password;
mClient.getCredentialsProvider().setCredentials(mAuthScope,
new UsernamePasswordCredentials(username, password));
isAuthenticationEnabled = true;
}
public Response post(String url, ArrayList<BasicNameValuePair> postParams,
boolean authenticated) throws HttpException {
if (null == postParams) {
postParams = new ArrayList<BasicNameValuePair>();
}
return httpRequest(url, postParams, authenticated, HttpPost.METHOD_NAME);
}
public Response post(String url, ArrayList<BasicNameValuePair> params)
throws HttpException {
return httpRequest(url, params, false, HttpPost.METHOD_NAME);
}
public Response post(String url, boolean authenticated)
throws HttpException {
return httpRequest(url, null, authenticated, HttpPost.METHOD_NAME);
}
public Response post(String url) throws HttpException {
return httpRequest(url, null, false, HttpPost.METHOD_NAME);
}
public Response post(String url, File file) throws HttpException {
return httpRequest(url, null, file, false, HttpPost.METHOD_NAME);
}
/**
* POST一个文件
*
* @param url
* @param file
* @param authenticate
* @return
* @throws HttpException
*/
public Response post(String url, File file, boolean authenticate)
throws HttpException {
return httpRequest(url, null, file, authenticate, HttpPost.METHOD_NAME);
}
public Response get(String url, ArrayList<BasicNameValuePair> params,
boolean authenticated) throws HttpException {
return httpRequest(url, params, authenticated, HttpGet.METHOD_NAME);
}
public Response get(String url, ArrayList<BasicNameValuePair> params)
throws HttpException {
return httpRequest(url, params, false, HttpGet.METHOD_NAME);
}
public Response get(String url) throws HttpException {
return httpRequest(url, null, false, HttpGet.METHOD_NAME);
}
public Response get(String url, boolean authenticated)
throws HttpException {
return httpRequest(url, null, authenticated, HttpGet.METHOD_NAME);
}
public Response httpRequest(String url,
ArrayList<BasicNameValuePair> postParams, boolean authenticated,
String httpMethod) throws HttpException {
return httpRequest(url, postParams, null, authenticated, httpMethod);
}
/**
* Execute the DefaultHttpClient
*
* @param url
* target
* @param postParams
* @param file
* can be NULL
* @param authenticated
* need or not
* @param httpMethod
* HttpPost.METHOD_NAME
* HttpGet.METHOD_NAME
* HttpDelete.METHOD_NAME
* @return Response from server
* @throws HttpException 此异常包装了一系列底层异常 <br /><br />
* 1. 底层异常, 可使用getCause()查看: <br />
* <li>URISyntaxException, 由`new URI` 引发的.</li>
* <li>IOException, 由`createMultipartEntity` 或 `UrlEncodedFormEntity` 引发的.</li>
* <li>IOException和ClientProtocolException, 由`HttpClient.execute` 引发的.</li><br />
*
* 2. 当响应码不为200时报出的各种子类异常:
* <li>HttpRequestException, 通常发生在请求的错误,如请求错误了 网址导致404等, 抛出此异常,
* 首先检查request log, 确认不是人为错误导致请求失败</li>
* <li>HttpAuthException, 通常发生在Auth失败, 检查用于验证登录的用户名/密码/KEY等</li>
* <li>HttpRefusedException, 通常发生在服务器接受到请求, 但拒绝请求, 可是多种原因, 具体原因
* 服务器会返回拒绝理由, 调用HttpRefusedException#getError#getMessage查看</li>
* <li>HttpServerException, 通常发生在服务器发生错误时, 检查服务器端是否在正常提供服务</li>
* <li>HttpException, 其他未知错误.</li>
*/
public Response httpRequest(String url, ArrayList<BasicNameValuePair> postParams,
File file, boolean authenticated, String httpMethod) throws HttpException {
Log.d(TAG, "Sending " + httpMethod + " request to " + url);
if (TwitterApplication.DEBUG){
DebugTimer.betweenStart("HTTP");
}
URI uri = createURI(url);
HttpResponse response = null;
Response res = null;
HttpUriRequest method = null;
// Create POST, GET or DELETE METHOD
method = createMethod(httpMethod, uri, file, postParams);
// Setup ConnectionParams, Request Headers
SetupHTTPConnectionParams(method);
// Execute Request
try {
response = mClient.execute(method, localcontext);
res = new Response(response);
} catch (ClientProtocolException e) {
Log.e(TAG, e.getMessage(), e);
throw new HttpException(e.getMessage(), e);
} catch (IOException ioe) {
throw new HttpException(ioe.getMessage(), ioe);
}
if (response != null) {
int statusCode = response.getStatusLine().getStatusCode();
// It will throw a weiboException while status code is not 200
HandleResponseStatusCode(statusCode, res);
} else {
Log.e(TAG, "response is null");
}
if (TwitterApplication.DEBUG){
DebugTimer.betweenEnd("HTTP");
}
return res;
}
/**
* CreateURI from URL string
*
* @param url
* @return request URI
* @throws HttpException
* Cause by URISyntaxException
*/
private URI createURI(String url) throws HttpException {
URI uri;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
Log.e(TAG, e.getMessage(), e);
throw new HttpException("Invalid URL.");
}
return uri;
}
/**
* 创建可带一个File的MultipartEntity
*
* @param filename
* 文件名
* @param file
* 文件
* @param postParams
* 其他POST参数
* @return 带文件和其他参数的Entity
* @throws UnsupportedEncodingException
*/
private MultipartEntity createMultipartEntity(String filename, File file,
ArrayList<BasicNameValuePair> postParams)
throws UnsupportedEncodingException {
MultipartEntity entity = new MultipartEntity();
// Don't try this. Server does not appear to support chunking.
// entity.addPart("media", new InputStreamBody(imageStream, "media"));
entity.addPart(filename, new FileBody(file));
for (BasicNameValuePair param : postParams) {
entity.addPart(param.getName(), new StringBody(param.getValue()));
}
return entity;
}
/**
* Setup HTTPConncetionParams
*
* @param method
*/
private void SetupHTTPConnectionParams(HttpUriRequest method) {
HttpConnectionParams.setConnectionTimeout(method.getParams(),
CONNECTION_TIMEOUT_MS);
HttpConnectionParams
.setSoTimeout(method.getParams(), SOCKET_TIMEOUT_MS);
mClient.setHttpRequestRetryHandler(requestRetryHandler);
method.addHeader("Accept-Encoding", "gzip, deflate");
method.addHeader("Accept-Charset", "UTF-8,*;q=0.5");
}
/**
* Create request method, such as POST, GET, DELETE
*
* @param httpMethod
* "GET","POST","DELETE"
* @param uri
* 请求的URI
* @param file
* 可为null
* @param postParams
* POST参数
* @return httpMethod Request implementations for the various HTTP methods
* like GET and POST.
* @throws HttpException
* createMultipartEntity 或 UrlEncodedFormEntity引发的IOException
*/
private HttpUriRequest createMethod(String httpMethod, URI uri, File file,
ArrayList<BasicNameValuePair> postParams) throws HttpException {
HttpUriRequest method;
if (httpMethod.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
// POST METHOD
HttpPost post = new HttpPost(uri);
// See this: http://groups.google.com/group/twitter-development-talk/browse_thread/thread/e178b1d3d63d8e3b
post.getParams().setBooleanParameter("http.protocol.expect-continue", false);
try {
HttpEntity entity = null;
if (null != file) {
entity = createMultipartEntity("photo", file, postParams);
post.setEntity(entity);
} else if (null != postParams) {
entity = new UrlEncodedFormEntity(postParams, HTTP.UTF_8);
}
post.setEntity(entity);
} catch (IOException ioe) {
throw new HttpException(ioe.getMessage(), ioe);
}
method = post;
} else if (httpMethod.equalsIgnoreCase(HttpDelete.METHOD_NAME)) {
method = new HttpDelete(uri);
} else {
method = new HttpGet(uri);
}
return method;
}
/**
* 解析HTTP错误码
*
* @param statusCode
* @return
*/
private static String getCause(int statusCode) {
String cause = null;
switch (statusCode) {
case NOT_MODIFIED:
break;
case BAD_REQUEST:
cause = "The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting.";
break;
case NOT_AUTHORIZED:
cause = "Authentication credentials were missing or incorrect.";
break;
case FORBIDDEN:
cause = "The request is understood, but it has been refused. An accompanying error message will explain why.";
break;
case NOT_FOUND:
cause = "The URI requested is invalid or the resource requested, such as a user, does not exists.";
break;
case NOT_ACCEPTABLE:
cause = "Returned by the Search API when an invalid format is specified in the request.";
break;
case INTERNAL_SERVER_ERROR:
cause = "Something is broken. Please post to the group so the Weibo team can investigate.";
break;
case BAD_GATEWAY:
cause = "Weibo is down or being upgraded.";
break;
case SERVICE_UNAVAILABLE:
cause = "Service Unavailable: The Weibo servers are up, but overloaded with requests. Try again later. The search and trend methods use this to indicate when you are being rate limited.";
break;
default:
cause = "";
}
return statusCode + ":" + cause;
}
public boolean isAuthenticationEnabled() {
return isAuthenticationEnabled;
}
public static void log(String msg) {
if (DEBUG) {
Log.d(TAG, msg);
}
}
/**
* Handle Status code
*
* @param statusCode
* 响应的状态码
* @param res
* 服务器响应
* @throws HttpException
* 当响应码不为200时都会报出此异常:<br />
* <li>HttpRequestException, 通常发生在请求的错误,如请求错误了 网址导致404等, 抛出此异常,
* 首先检查request log, 确认不是人为错误导致请求失败</li>
* <li>HttpAuthException, 通常发生在Auth失败, 检查用于验证登录的用户名/密码/KEY等</li>
* <li>HttpRefusedException, 通常发生在服务器接受到请求, 但拒绝请求, 可是多种原因, 具体原因
* 服务器会返回拒绝理由, 调用HttpRefusedException#getError#getMessage查看</li>
* <li>HttpServerException, 通常发生在服务器发生错误时, 检查服务器端是否在正常提供服务</li>
* <li>HttpException, 其他未知错误.</li>
*/
private void HandleResponseStatusCode(int statusCode, Response res)
throws HttpException {
String msg = getCause(statusCode) + "\n";
RefuseError error = null;
switch (statusCode) {
// It's OK, do nothing
case OK:
break;
// Mine mistake, Check the Log
case NOT_MODIFIED:
case BAD_REQUEST:
case NOT_FOUND:
case NOT_ACCEPTABLE:
throw new HttpException(msg + res.asString(), statusCode);
// UserName/Password incorrect
case NOT_AUTHORIZED:
throw new HttpAuthException(msg + res.asString(), statusCode);
// Server will return a error message, use
// HttpRefusedException#getError() to see.
case FORBIDDEN:
throw new HttpRefusedException(msg, statusCode);
// Something wrong with server
case INTERNAL_SERVER_ERROR:
case BAD_GATEWAY:
case SERVICE_UNAVAILABLE:
throw new HttpServerException(msg, statusCode);
// Others
default:
throw new HttpException(msg + res.asString(), statusCode);
}
}
public static String encode(String value) throws HttpException {
try {
return URLEncoder.encode(value, HTTP.UTF_8);
} catch (UnsupportedEncodingException e_e) {
throw new HttpException(e_e.getMessage(), e_e);
}
}
public static String encodeParameters(ArrayList<BasicNameValuePair> params)
throws HttpException {
StringBuffer buf = new StringBuffer();
for (int j = 0; j < params.size(); j++) {
if (j != 0) {
buf.append("&");
}
try {
buf.append(URLEncoder.encode(params.get(j).getName(), "UTF-8"))
.append("=")
.append(URLEncoder.encode(params.get(j).getValue(),
"UTF-8"));
} catch (java.io.UnsupportedEncodingException neverHappen) {
throw new HttpException(neverHappen.getMessage(), neverHappen);
}
}
return buf.toString();
}
/**
* 异常自动恢复处理, 使用HttpRequestRetryHandler接口实现请求的异常恢复
*/
private static HttpRequestRetryHandler requestRetryHandler = new HttpRequestRetryHandler() {
// 自定义的恢复策略
public boolean retryRequest(IOException exception, int executionCount,
HttpContext context) {
// 设置恢复策略,在发生异常时候将自动重试N次
if (executionCount >= RETRIED_TIME) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof NoHttpResponseException) {
// Retry if the server dropped connection on us
return true;
}
if (exception instanceof SSLHandshakeException) {
// Do not retry on SSL handshake exception
return false;
}
HttpRequest request = (HttpRequest) context
.getAttribute(ExecutionContext.HTTP_REQUEST);
boolean idempotent = (request instanceof HttpEntityEnclosingRequest);
if (!idempotent) {
// Retry if the request is considered idempotent
return true;
}
return false;
}
};
}
| Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid.ui.base;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.fanfou.IDs;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskManager;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.module.FlingGestureListener;
import com.ch_linghu.fanfoudroid.ui.module.MyActivityFlipper;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
import com.ch_linghu.fanfoudroid.ui.module.TweetCursorAdapter;
import com.ch_linghu.fanfoudroid.ui.module.Widget;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.DebugTimer;
import com.hlidskialf.android.hardware.ShakeListener;
/**
* TwitterCursorBaseLine用于带有静态数据来源(对应数据库的,与twitter表同构的特定表)的展现
*/
public abstract class TwitterCursorBaseActivity extends TwitterListBaseActivity {
static final String TAG = "TwitterCursorBaseActivity";
// Views.
protected ListView mTweetList;
protected TweetCursorAdapter mTweetAdapter;
protected View mListHeader;
protected View mListFooter;
protected TextView loadMoreBtn;
protected ProgressBar loadMoreGIF;
protected TextView loadMoreBtnTop;
protected ProgressBar loadMoreGIFTop;
protected static int lastPosition = 0;
protected ShakeListener mShaker = null;
// Tasks.
protected TaskManager taskManager = new TaskManager();
private GenericTask mRetrieveTask;
private GenericTask mFollowersRetrieveTask;
private GenericTask mGetMoreTask;
private int mRetrieveCount = 0;
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "RetrieveTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
mFeedback.failed("登录信息出错");
logout();
} else if (result == TaskResult.OK) {
// TODO: XML处理, GC压力
SharedPreferences.Editor editor = getPreferences().edit();
editor.putLong(Preferences.LAST_TWEET_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
// TODO: 1. StatusType(DONE) ;
if (mRetrieveCount >= StatusTable.MAX_ROW_NUM) {
// 只有在取回的数据大于MAX时才做GC, 因为小于时可以保证数据的连续性
getDb().gc(getUserId(), getDatabaseType()); // GC
}
draw();
if (task == mRetrieveTask) {
goTop();
}
} else if (result == TaskResult.IO_ERROR) {
// FIXME: bad smell
if (task == mRetrieveTask) {
mFeedback.failed(((RetrieveTask) task).getErrorMsg());
} else if (task == mGetMoreTask) {
mFeedback.failed(((GetMoreTask) task).getErrorMsg());
}
} else {
// do nothing
}
// 刷新按钮停止旋转
loadMoreGIFTop.setVisibility(View.GONE);
loadMoreGIF.setVisibility(View.GONE);
// DEBUG
if (TwitterApplication.DEBUG) {
DebugTimer.stop();
Log.v("DEBUG", DebugTimer.getProfileAsString());
}
}
@Override
public void onPreExecute(GenericTask task) {
mRetrieveCount = 0;
if (TwitterApplication.DEBUG) {
DebugTimer.start();
}
}
@Override
public void onProgressUpdate(GenericTask task, Object param) {
Log.d(TAG, "onProgressUpdate");
draw();
}
};
private TaskListener mFollowerRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "FollowerRetrieve";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
SharedPreferences sp = getPreferences();
SharedPreferences.Editor editor = sp.edit();
editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
} else {
// Do nothing.
}
}
};
// Refresh data at startup if last refresh was this long ago or greater.
private static final long REFRESH_THRESHOLD = 5 * 60 * 1000;
// Refresh followers if last refresh was this long ago or greater.
private static final long FOLLOWERS_REFRESH_THRESHOLD = 12 * 60 * 60 * 1000;
abstract protected void markAllRead();
abstract protected Cursor fetchMessages();
public abstract int getDatabaseType();
public abstract String getUserId();
public abstract String fetchMaxId();
public abstract String fetchMinId();
public abstract int addMessages(ArrayList<Tweet> tweets, boolean isUnread);
public abstract List<Status> getMessageSinceId(String maxId)
throws HttpException;
public abstract List<Status> getMoreMessageFromId(String minId)
throws HttpException;
public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1;
// public static final int CONTEXT_AT_ID = Menu.FIRST + 2;
public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3;
public static final int CONTEXT_DM_ID = Menu.FIRST + 4;
public static final int CONTEXT_MORE_ID = Menu.FIRST + 5;
public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6;
public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7;
@Override
protected void setupState() {
Cursor cursor;
cursor = fetchMessages(); // getDb().fetchMentions();
setTitle(getActivityTitle());
startManagingCursor(cursor);
mTweetList = (ListView) findViewById(R.id.tweet_list);
// TODO: 需处理没有数据时的情况
Log.d("LDS", cursor.getCount() + " cursor count");
setupListHeader(true);
mTweetAdapter = new TweetCursorAdapter(this, cursor);
mTweetList.setAdapter(mTweetAdapter);
// ? registerOnClickListener(mTweetList);
}
/**
* 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用
*/
protected void setupListHeader(boolean addFooter) {
// Add Header to ListView
mListHeader = View.inflate(this, R.layout.listview_header, null);
mTweetList.addHeaderView(mListHeader, null, true);
// Add Footer to ListView
mListFooter = View.inflate(this, R.layout.listview_footer, null);
mTweetList.addFooterView(mListFooter, null, true);
// Find View
loadMoreBtn = (TextView) findViewById(R.id.ask_for_more);
loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar);
loadMoreBtnTop = (TextView) findViewById(R.id.ask_for_more_header);
loadMoreGIFTop = (ProgressBar) findViewById(R.id.rectangleProgressBar_header);
}
@Override
protected void specialItemClicked(int position) {
// 注意 mTweetAdapter.getCount 和 mTweetList.getCount的区别
// 前者仅包含数据的数量(不包括foot和head),后者包含foot和head
// 因此在同时存在foot和head的情况下,list.count = adapter.count + 2
if (position == 0) {
// 第一个Item(header)
loadMoreGIFTop.setVisibility(View.VISIBLE);
doRetrieve();
} else if (position == mTweetList.getCount() - 1) {
// 最后一个Item(footer)
loadMoreGIF.setVisibility(View.VISIBLE);
doGetMore();
}
}
@Override
protected int getLayoutId() {
return R.layout.main;
}
@Override
protected ListView getTweetList() {
return mTweetList;
}
@Override
protected TweetAdapter getTweetAdapter() {
return mTweetAdapter;
}
@Override
protected boolean useBasicMenu() {
return true;
}
@Override
protected Tweet getContextItemTweet(int position) {
position = position - 1;
// 因为List加了Header和footer,所以要跳过第一个以及忽略最后一个
if (position >= 0 && position < mTweetAdapter.getCount()) {
Cursor cursor = (Cursor) mTweetAdapter.getItem(position);
if (cursor == null) {
return null;
} else {
return StatusTable.parseCursor(cursor);
}
} else {
return null;
}
}
@Override
protected void updateTweet(Tweet tweet) {
// TODO: updateTweet() 在哪里调用的? 目前尚只支持:
// updateTweet(String tweetId, ContentValues values)
// setFavorited(String tweetId, String isFavorited)
// 看是否还需要增加updateTweet(Tweet tweet)方法
// 对所有相关表的对应消息都进行刷新(如果存在的话)
// getDb().updateTweet(TwitterDbAdapter.TABLE_FAVORITE, tweet);
// getDb().updateTweet(TwitterDbAdapter.TABLE_MENTION, tweet);
// getDb().updateTweet(TwitterDbAdapter.TABLE_TWEET, tweet);
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)) {
goTop(); // skip the header
// Mark all as read.
// getDb().markAllMentionsRead();
markAllRead();
boolean shouldRetrieve = false;
// FIXME: 该子类页面全部使用了这个统一的计时器,导致进入Mention等分页面后经常不会自动刷新
long lastRefreshTime = mPreferences.getLong(
Preferences.LAST_TWEET_REFRESH_KEY, 0);
long nowTime = DateTimeHelper.getNowTime();
long diff = nowTime - lastRefreshTime;
Log.d(TAG, "Last refresh was " + diff + " ms ago.");
if (diff > REFRESH_THRESHOLD) {
shouldRetrieve = true;
} else if (isTrue(savedInstanceState, SIS_RUNNING_KEY)) {
// Check to see if it was running a send or retrieve task.
// It makes no sense to resend the send request (don't want
// dupes)
// so we instead retrieve (refresh) to see if the message has
// posted.
Log.d(TAG,
"Was last running a retrieve or send task. Let's refresh.");
shouldRetrieve = true;
}
if (shouldRetrieve) {
doRetrieve();
}
long lastFollowersRefreshTime = mPreferences.getLong(
Preferences.LAST_FOLLOWERS_REFRESH_KEY, 0);
diff = nowTime - lastFollowersRefreshTime;
Log.d(TAG, "Last followers refresh was " + diff + " ms ago.");
// FIXME: 目前还没有对Followers列表做逻辑处理,因此暂时去除对Followers的获取。
// 未来需要实现@用户提示时,对Follower操作需要做一次review和refactoring
// 现在频繁会出现主键冲突的问题。
//
// Should Refresh Followers
// if (diff > FOLLOWERS_REFRESH_THRESHOLD
// && (mRetrieveTask == null || mRetrieveTask.getStatus() !=
// GenericTask.Status.RUNNING)) {
// Log.d(TAG, "Refresh followers.");
// doRetrieveFollowers();
// }
// 手势识别
registerGestureListener();
//晃动刷新
registerShakeListener();
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
Log.d(TAG, "onResume.");
if (lastPosition != 0) {
mTweetList.setSelection(lastPosition);
}
if (mShaker != null){
mShaker.resume();
}
super.onResume();
checkIsLogedIn();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
@Override
protected void onRestoreInstanceState(Bundle bundle) {
super.onRestoreInstanceState(bundle);
// mTweetEdit.updateCharsRemain();
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
super.onDestroy();
taskManager.cancelAll();
}
@Override
protected void onPause() {
Log.d(TAG, "onPause.");
if (mShaker != null){
mShaker.pause();
}
super.onPause();
lastPosition = mTweetList.getFirstVisiblePosition();
}
@Override
protected void onRestart() {
Log.d(TAG, "onRestart.");
super.onRestart();
}
@Override
protected void onStart() {
Log.d(TAG, "onStart.");
super.onStart();
}
@Override
protected void onStop() {
Log.d(TAG, "onStop.");
super.onStop();
}
// UI helpers.
@Override
protected String getActivityTitle() {
return null;
}
@Override
protected void adapterRefresh() {
mTweetAdapter.notifyDataSetChanged();
mTweetAdapter.refresh();
}
// Retrieve interface
public void updateProgress(String progress) {
mProgressText.setText(progress);
}
public void draw() {
mTweetAdapter.refresh();
}
public void goTop() {
Log.d(TAG, "goTop.");
mTweetList.setSelection(1);
}
private void doRetrieveFollowers() {
Log.d(TAG, "Attempting followers retrieve.");
if (mFollowersRetrieveTask != null
&& mFollowersRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mFollowersRetrieveTask = new FollowersRetrieveTask();
mFollowersRetrieveTask.setListener(mFollowerRetrieveTaskListener);
mFollowersRetrieveTask.execute();
taskManager.addTask(mFollowersRetrieveTask);
// Don't need to cancel FollowersTask (assuming it ends properly).
mFollowersRetrieveTask.setCancelable(false);
}
}
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new RetrieveTask();
mRetrieveTask.setFeedback(mFeedback);
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute();
// Add Task to manager
taskManager.addTask(mRetrieveTask);
}
}
private class RetrieveTask extends GenericTask {
private String _errorMsg;
public String getErrorMsg() {
return _errorMsg;
}
@Override
protected TaskResult _doInBackground(TaskParams... params) {
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
try {
String maxId = fetchMaxId(); // getDb().fetchMaxMentionId();
statusList = getMessageSinceId(maxId);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
_errorMsg = e.getMessage();
return TaskResult.IO_ERROR;
}
ArrayList<Tweet> tweets = new ArrayList<Tweet>();
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
tweets.add(Tweet.create(status));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, tweets));
mRetrieveCount = addMessages(tweets, false);
return TaskResult.OK;
}
}
private class FollowersRetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
// TODO: 目前仅做新API兼容性改动,待完善Follower处理
IDs followers = getApi().getFollowersIDs();
List<String> followerIds = Arrays.asList(followers.getIDs());
getDb().syncFollowers(followerIds);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
// GET MORE TASK
private class GetMoreTask extends GenericTask {
private String _errorMsg;
public String getErrorMsg() {
return _errorMsg;
}
@Override
protected TaskResult _doInBackground(TaskParams... params) {
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
String minId = fetchMinId(); // getDb().fetchMaxMentionId();
if (minId == null) {
return TaskResult.FAILED;
}
try {
statusList = getMoreMessageFromId(minId);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
_errorMsg = e.getMessage();
return TaskResult.IO_ERROR;
}
if (statusList == null) {
return TaskResult.FAILED;
}
ArrayList<Tweet> tweets = new ArrayList<Tweet>();
publishProgress(SimpleFeedback.calProgressBySize(40, 20, tweets));
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
tweets.add(Tweet.create(status));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addMessages(tweets, false); // getDb().addMentions(tweets, false);
return TaskResult.OK;
}
}
public void doGetMore() {
Log.d(TAG, "Attempting getMore.");
if (mGetMoreTask != null
&& mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mGetMoreTask = new GetMoreTask();
mGetMoreTask.setFeedback(mFeedback);
mGetMoreTask.setListener(mRetrieveTaskListener);
mGetMoreTask.execute();
// Add Task to manager
taskManager.addTask(mGetMoreTask);
}
}
//////////////////// Gesture test /////////////////////////////////////
private static boolean useGestrue;
{
useGestrue = TwitterApplication.mPref.getBoolean(
Preferences.USE_GESTRUE, false);
if (useGestrue) {
Log.v(TAG, "Using Gestrue!");
} else {
Log.v(TAG, "Not Using Gestrue!");
}
}
//////////////////// Gesture test /////////////////////////////////////
private static boolean useShake;
{
useShake = TwitterApplication.mPref.getBoolean(
Preferences.USE_SHAKE, false);
if (useShake) {
Log.v(TAG, "Using Shake to refresh!");
} else {
Log.v(TAG, "Not Using Shake!");
}
}
protected FlingGestureListener myGestureListener = null;
@Override
public boolean onTouchEvent(MotionEvent event) {
if (useGestrue && myGestureListener != null) {
return myGestureListener.getDetector().onTouchEvent(event);
}
return super.onTouchEvent(event);
}
// use it in _onCreate
private void registerGestureListener() {
if (useGestrue) {
myGestureListener = new FlingGestureListener(this,
MyActivityFlipper.create(this));
getTweetList().setOnTouchListener(myGestureListener);
}
}
// use it in _onCreate
private void registerShakeListener() {
if (useShake){
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener() {
@Override
public void onShake() {
doRetrieve();
}
});
}
}
} | Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid.ui.base;
import java.util.ArrayList;
import java.util.List;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.db.UserInfoTable;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskManager;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
import com.ch_linghu.fanfoudroid.ui.module.UserCursorAdapter;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
/**
* TwitterCursorBaseLine用于带有静态数据来源(对应数据库的,与twitter表同构的特定表)的展现
*/
public abstract class UserCursorBaseActivity extends UserListBaseActivity {
/**
* 第一种方案:(采取第一种) 暂不放在数据库中,直接从Api读取。
*
* 第二种方案: 麻烦的是api数据与数据库同步,当收听人数比较多的时候,一次性读取太费流量 按照饭否api每次分页100人
* 当收听数<100时先从数据库一次性根据API返回的ID列表读取数据,如果数据库中的收听数<总数,那么从API中读取所有用户信息并同步到数据库中。
* 当收听数>100时采取分页加载,先按照id
* 获取数据库里前100用户,如果用户数量<100则从api中加载,从page=1开始下载,同步到数据库中,单击更多继续从数据库中加载
* 当数据库中的数据读取到最后一页后,则从api中加载并更新到数据库中。 单击刷新按钮则从api加载并同步到数据库中
*
*/
static final String TAG = "UserCursorBaseActivity";
// Views.
protected ListView mUserList;
protected UserCursorAdapter mUserListAdapter;
protected TextView loadMoreBtn;
protected ProgressBar loadMoreGIF;
protected TextView loadMoreBtnTop;
protected ProgressBar loadMoreGIFTop;
protected static int lastPosition = 0;
// Tasks.
protected TaskManager taskManager = new TaskManager();
private GenericTask mRetrieveTask;
private GenericTask mFollowersRetrieveTask;
private GenericTask mGetMoreTask;// 每次十个用户
protected abstract String getUserId();// 获得用户id
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "RetrieveTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
SharedPreferences.Editor editor = getPreferences().edit();
editor.putLong(Preferences.LAST_TWEET_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
// TODO: 1. StatusType(DONE) ; 2. 只有在取回的数据大于MAX时才做GC,
// 因为小于时可以保证数据的连续性
// FIXME: gc需要带owner
// getDb().gc(getDatabaseType()); // GC
draw();
goTop();
} else {
// Do nothing.
}
// loadMoreGIFTop.setVisibility(View.GONE);
updateProgress("");
}
@Override
public void onPreExecute(GenericTask task) {
onRetrieveBegin();
}
@Override
public void onProgressUpdate(GenericTask task, Object param) {
Log.d(TAG, "onProgressUpdate");
draw();
}
};
private TaskListener mFollowerRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "FollowerRetrieve";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
SharedPreferences sp = getPreferences();
SharedPreferences.Editor editor = sp.edit();
editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
} else {
// Do nothing.
}
}
};
// Refresh data at startup if last refresh was this long ago or greater.
private static final long REFRESH_THRESHOLD = 5 * 60 * 1000;
// Refresh followers if last refresh was this long ago or greater.
private static final long FOLLOWERS_REFRESH_THRESHOLD = 12 * 60 * 60 * 1000;
abstract protected Cursor fetchUsers();
public abstract int getDatabaseType();
public abstract String fetchMaxId();
public abstract String fetchMinId();
public abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers()
throws HttpException;
public abstract void addUsers(
ArrayList<com.ch_linghu.fanfoudroid.data.User> tusers);
// public abstract List<Status> getMessageSinceId(String maxId)
// throws WeiboException;
public abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUserSinceId(
String maxId) throws HttpException;
public abstract List<Status> getMoreMessageFromId(String minId)
throws HttpException;
public abstract Paging getNextPage();// 下一页数
public abstract Paging getCurrentPage();// 当前页数
protected abstract String[] getIds();
public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1;
// public static final int CONTEXT_AT_ID = Menu.FIRST + 2;
public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3;
public static final int CONTEXT_DM_ID = Menu.FIRST + 4;
public static final int CONTEXT_MORE_ID = Menu.FIRST + 5;
public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6;
public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7;
@Override
protected void setupState() {
Cursor cursor;
cursor = fetchUsers(); //
setTitle(getActivityTitle());
startManagingCursor(cursor);
mUserList = (ListView) findViewById(R.id.follower_list);
// TODO: 需处理没有数据时的情况
Log.d("LDS", cursor.getCount() + " cursor count");
setupListHeader(true);
mUserListAdapter = new UserCursorAdapter(this, cursor);
mUserList.setAdapter(mUserListAdapter);
// ? registerOnClickListener(mTweetList);
}
/**
* 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用
*/
protected void setupListHeader(boolean addFooter) {
// Add footer to Listview
View footer = View.inflate(this, R.layout.listview_footer, null);
mUserList.addFooterView(footer, null, true);
// Find View
loadMoreBtn = (TextView) findViewById(R.id.ask_for_more);
loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar);
// loadMoreBtnTop = (TextView)findViewById(R.id.ask_for_more_header);
// loadMoreGIFTop =
// (ProgressBar)findViewById(R.id.rectangleProgressBar_header);
// loadMoreAnimation = (AnimationDrawable)
// loadMoreGIF.getIndeterminateDrawable();
}
@Override
protected void specialItemClicked(int position) {
if (position == mUserList.getCount() - 1) {
// footer
loadMoreGIF.setVisibility(View.VISIBLE);
doGetMore();
}
}
@Override
protected int getLayoutId() {
return R.layout.follower;
}
@Override
protected ListView getUserList() {
return mUserList;
}
@Override
protected TweetAdapter getUserAdapter() {
return mUserListAdapter;
}
@Override
protected boolean useBasicMenu() {
return true;
}
protected User getContextItemUser(int position) {
// position = position - 1;
// 加入footer跳过footer
if (position < mUserListAdapter.getCount()) {
Cursor cursor = (Cursor) mUserListAdapter.getItem(position);
if (cursor == null) {
return null;
} else {
return UserInfoTable.parseCursor(cursor);
}
} else {
return null;
}
}
@Override
protected void updateTweet(Tweet tweet) {
// TODO: updateTweet() 在哪里调用的? 目前尚只支持:
// updateTweet(String tweetId, ContentValues values)
// setFavorited(String tweetId, String isFavorited)
// 看是否还需要增加updateTweet(Tweet tweet)方法
// 对所有相关表的对应消息都进行刷新(如果存在的话)
// getDb().updateTweet(TwitterDbAdapter.TABLE_FAVORITE, tweet);
// getDb().updateTweet(TwitterDbAdapter.TABLE_MENTION, tweet);
// getDb().updateTweet(TwitterDbAdapter.TABLE_TWEET, tweet);
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)) {
goTop(); // skip the header
boolean shouldRetrieve = false;
// FIXME: 该子类页面全部使用了这个统一的计时器,导致进入Mention等分页面后经常不会自动刷新
long lastRefreshTime = mPreferences.getLong(
Preferences.LAST_TWEET_REFRESH_KEY, 0);
long nowTime = DateTimeHelper.getNowTime();
long diff = nowTime - lastRefreshTime;
Log.d(TAG, "Last refresh was " + diff + " ms ago.");
/*
* if (diff > REFRESH_THRESHOLD) { shouldRetrieve = true; } else if
* (Utils.isTrue(savedInstanceState, SIS_RUNNING_KEY)) { // Check to
* see if it was running a send or retrieve task. // It makes no
* sense to resend the send request (don't want dupes) // so we
* instead retrieve (refresh) to see if the message has // posted.
* Log.d(TAG,
* "Was last running a retrieve or send task. Let's refresh.");
* shouldRetrieve = true; }
*/
shouldRetrieve = true;
if (shouldRetrieve) {
doRetrieve();
}
long lastFollowersRefreshTime = mPreferences.getLong(
Preferences.LAST_FOLLOWERS_REFRESH_KEY, 0);
diff = nowTime - lastFollowersRefreshTime;
Log.d(TAG, "Last followers refresh was " + diff + " ms ago.");
/*
* if (diff > FOLLOWERS_REFRESH_THRESHOLD && (mRetrieveTask == null
* || mRetrieveTask.getStatus() != GenericTask.Status.RUNNING)) {
* Log.d(TAG, "Refresh followers."); doRetrieveFollowers(); }
*/
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
Log.d(TAG, "onResume.");
if (lastPosition != 0) {
mUserList.setSelection(lastPosition);
}
super.onResume();
checkIsLogedIn();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
@Override
protected void onRestoreInstanceState(Bundle bundle) {
super.onRestoreInstanceState(bundle);
// mTweetEdit.updateCharsRemain();
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
super.onDestroy();
taskManager.cancelAll();
}
@Override
protected void onPause() {
Log.d(TAG, "onPause.");
super.onPause();
lastPosition = mUserList.getFirstVisiblePosition();
}
@Override
protected void onRestart() {
Log.d(TAG, "onRestart.");
super.onRestart();
}
@Override
protected void onStart() {
Log.d(TAG, "onStart.");
super.onStart();
}
@Override
protected void onStop() {
Log.d(TAG, "onStop.");
super.onStop();
}
// UI helpers.
@Override
protected String getActivityTitle() {
// TODO Auto-generated method stub
return null;
}
@Override
protected void adapterRefresh() {
mUserListAdapter.notifyDataSetChanged();
mUserListAdapter.refresh();
}
// Retrieve interface
public void updateProgress(String progress) {
mProgressText.setText(progress);
}
public void draw() {
mUserListAdapter.refresh();
}
public void goTop() {
Log.d(TAG, "goTop.");
mUserList.setSelection(1);
}
private void doRetrieveFollowers() {
Log.d(TAG, "Attempting followers retrieve.");
if (mFollowersRetrieveTask != null
&& mFollowersRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mFollowersRetrieveTask = new FollowersRetrieveTask();
mFollowersRetrieveTask.setListener(mFollowerRetrieveTaskListener);
mFollowersRetrieveTask.execute();
taskManager.addTask(mFollowersRetrieveTask);
// Don't need to cancel FollowersTask (assuming it ends properly).
mFollowersRetrieveTask.setCancelable(false);
}
}
public void onRetrieveBegin() {
updateProgress(getString(R.string.page_status_refreshing));
}
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new RetrieveTask();
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.setFeedback(mFeedback);
mRetrieveTask.execute();
// Add Task to manager
taskManager.addTask(mRetrieveTask);
}
}
/**
* TODO:从API获取当前Followers,并同步到数据库
*
* @author Dino
*
*/
private class RetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
Log.d(TAG, "load RetrieveTask");
List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null;
try {
usersList = getApi().getFollowersList(getUserId(),
getCurrentPage());
} catch (HttpException e) {
e.printStackTrace();
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList));
ArrayList<User> users = new ArrayList<User>();
for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
users.add(User.create(user));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addUsers(users);
return TaskResult.OK;
}
}
private class FollowersRetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
Log.d(TAG, "load FollowersErtrieveTask");
List<com.ch_linghu.fanfoudroid.fanfou.User> t_users = getUsers();
getDb().syncWeiboUsers(t_users);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
/**
* TODO:需要重写,获取下一批用户,按页分100页一次
*
* @author Dino
*
*/
private class GetMoreTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
Log.d(TAG, "load RetrieveTask");
List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null;
try {
usersList = getApi().getFollowersList(getUserId(),
getNextPage());
} catch (HttpException e) {
e.printStackTrace();
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList));
ArrayList<User> users = new ArrayList<User>();
for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
users.add(User.create(user));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addUsers(users);
return TaskResult.OK;
}
}
private TaskListener getMoreListener = new TaskAdapter() {
@Override
public String getName() {
return "getMore";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
super.onPostExecute(task, result);
draw();
loadMoreGIF.setVisibility(View.GONE);
}
};
public void doGetMore() {
Log.d(TAG, "Attempting getMore.");
if (mGetMoreTask != null
&& mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mGetMoreTask = new GetMoreTask();
mGetMoreTask.setFeedback(mFeedback);
mGetMoreTask.setListener(getMoreListener);
mGetMoreTask.execute();
// Add Task to manager
taskManager.addTask(mGetMoreTask);
}
}
} | Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* AbstractTwitterListBaseLine用于抽象tweets List的展现
* UI基本元素要求:一个ListView用于tweet列表
* 一个ProgressText用于提示信息
*/
package com.ch_linghu.fanfoudroid.ui.base;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.DmActivity;
import com.ch_linghu.fanfoudroid.MentionActivity;
import com.ch_linghu.fanfoudroid.ProfileActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.StatusActivity;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.WriteActivity;
import com.ch_linghu.fanfoudroid.WriteDmActivity;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.task.TweetCommonTask;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
public abstract class TwitterListBaseActivity extends BaseActivity
implements Refreshable {
static final String TAG = "TwitterListBaseActivity";
protected TextView mProgressText;
protected Feedback mFeedback;
protected NavBar mNavbar;
protected static final int STATE_ALL = 0;
protected static final String SIS_RUNNING_KEY = "running";
// Tasks.
protected GenericTask mFavTask;
private TaskListener mFavTaskListener = new TaskAdapter(){
@Override
public String getName() {
return "FavoriteTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onFavSuccess();
} else if (result == TaskResult.IO_ERROR) {
onFavFailure();
}
}
};
static final int DIALOG_WRITE_ID = 0;
abstract protected int getLayoutId();
abstract protected ListView getTweetList();
abstract protected TweetAdapter getTweetAdapter();
abstract protected void setupState();
abstract protected String getActivityTitle();
abstract protected boolean useBasicMenu();
abstract protected Tweet getContextItemTweet(int position);
abstract protected void updateTweet(Tweet tweet);
public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1;
// public static final int CONTEXT_AT_ID = Menu.FIRST + 2;
public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3;
public static final int CONTEXT_DM_ID = Menu.FIRST + 4;
public static final int CONTEXT_MORE_ID = Menu.FIRST + 5;
public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6;
public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7;
/**
* 如果增加了Context Menu常量的数量,则必须重载此方法,
* 以保证其他人使用常量时不产生重复
* @return 最大的Context Menu常量
*/
protected int getLastContextMenuId(){
return CONTEXT_DEL_FAV_ID;
}
@Override
protected boolean _onCreate(Bundle savedInstanceState){
if (super._onCreate(savedInstanceState)){
setContentView(getLayoutId());
mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this);
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
mPreferences.getInt(Preferences.TWITTER_ACTIVITY_STATE_KEY, STATE_ALL);
// 提示栏
mProgressText = (TextView) findViewById(R.id.progress_text);
setupState();
registerForContextMenu(getTweetList());
registerOnClickListener(getTweetList());
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) {
mFavTask.cancel(true);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
Log.d("FLING", "onContextItemSelected");
super.onCreateContextMenu(menu, v, menuInfo);
if (useBasicMenu()){
AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
Tweet tweet = getContextItemTweet(info.position);
if (tweet == null) {
Log.w(TAG, "Selected item not available.");
return;
}
menu.add(0, CONTEXT_MORE_ID, 0, tweet.screenName + getResources().getString(R.string.cmenu_user_profile_prefix));
menu.add(0, CONTEXT_REPLY_ID, 0, R.string.cmenu_reply);
menu.add(0, CONTEXT_RETWEET_ID, 0, R.string.cmenu_retweet);
menu.add(0, CONTEXT_DM_ID, 0, R.string.cmenu_direct_message);
if (tweet.favorited.equals("true")) {
menu.add(0, CONTEXT_DEL_FAV_ID, 0, R.string.cmenu_del_fav);
} else {
menu.add(0, CONTEXT_ADD_FAV_ID, 0, R.string.cmenu_add_fav);
}
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
Tweet tweet = getContextItemTweet(info.position);
if (tweet == null) {
Log.w(TAG, "Selected item not available.");
return super.onContextItemSelected(item);
}
switch (item.getItemId()) {
case CONTEXT_MORE_ID:
launchActivity(ProfileActivity.createIntent(tweet.userId));
return true;
case CONTEXT_REPLY_ID: {
// TODO: this isn't quite perfect. It leaves extra empty spaces if
// you perform the reply action again.
Intent intent = WriteActivity.createNewReplyIntent(tweet.text, tweet.screenName, tweet.id);
startActivity(intent);
return true;
}
case CONTEXT_RETWEET_ID:
Intent intent = WriteActivity.createNewRepostIntent(this,
tweet.text, tweet.screenName, tweet.id);
startActivity(intent);
return true;
case CONTEXT_DM_ID:
launchActivity(WriteDmActivity.createIntent(tweet.userId));
return true;
case CONTEXT_ADD_FAV_ID:
doFavorite("add", tweet.id);
return true;
case CONTEXT_DEL_FAV_ID:
doFavorite("del", tweet.id);
return true;
default:
return super.onContextItemSelected(item);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case OPTIONS_MENU_ID_TWEETS:
launchActivity(TwitterActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_REPLIES:
launchActivity(MentionActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_DM:
launchActivity(DmActivity.createIntent());
return true;
}
return super.onOptionsItemSelected(item);
}
protected void draw() {
getTweetAdapter().refresh();
}
protected void goTop() {
getTweetList().setSelection(1);
}
protected void adapterRefresh(){
getTweetAdapter().refresh();
}
// for HasFavorite interface
public void doFavorite(String action, String id) {
if (!TextUtils.isEmpty(id)) {
if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING){
return;
}else{
mFavTask = new TweetCommonTask.FavoriteTask(this);
mFavTask.setListener(mFavTaskListener);
TaskParams params = new TaskParams();
params.put("action", action);
params.put("id", id);
mFavTask.execute(params);
}
}
}
public void onFavSuccess() {
// updateProgress(getString(R.string.refreshing));
adapterRefresh();
}
public void onFavFailure() {
// updateProgress(getString(R.string.refreshing));
}
protected void specialItemClicked(int position){
}
protected void registerOnClickListener(ListView listView) {
listView.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Tweet tweet = getContextItemTweet(position);
if (tweet == null) {
Log.w(TAG, "Selected item not available.");
specialItemClicked(position);
}else{
launchActivity(StatusActivity.createIntent(tweet));
}
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
} | Java |
package com.ch_linghu.fanfoudroid.ui.base;
import android.app.ListActivity;
/**
* TODO: 准备重构现有的几个ListActivity
*
* 目前几个ListActivity存在的问题是 :
* 1. 因为要实现[刷新]这些功能, 父类设定了子类继承时必须要实现的方法,
* 而刷新/获取其实更多的时候可以理解成是ListView的层面, 这在于讨论到底是一个"可刷新的Activity"
* 还是一个拥有"可刷新的ListView"的Activity, 如果改成后者, 则只要在父类拥有一个实现了可刷新接口的ListView即可,
* 而无需强制要求子类去直接实现某些方法.
* 2. 父类过于专制, 比如getLayoutId()等抽象方法的存在只是为了在父类进行setContentView, 而此类方法可以下放到子类去自行实现,
* 诸如此类的, 应该下放给子类更自由的空间. 理想状态为不使用抽象类.
* 3. 随着功能扩展, 需要将几个不同的ListActivity子类重复的部分重新抽象到父类来, 已减少代码重复.
* 4. TwitterList和UserList代码存在重复现象, 可抽象.
* 5. TwitterList目前过于依赖Cursor类型的List, 而没有Array类型的抽象类.
*
*/
public class BaseListActivity extends ListActivity {
}
| Java |
package com.ch_linghu.fanfoudroid.ui.base;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.ch_linghu.fanfoudroid.AboutActivity;
import com.ch_linghu.fanfoudroid.LoginActivity;
import com.ch_linghu.fanfoudroid.PreferencesActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.Weibo;
import com.ch_linghu.fanfoudroid.service.TwitterService;
/**
* A BaseActivity has common routines and variables for an Activity that
* contains a list of tweets and a text input field.
*
* Not the cleanest design, but works okay for several Activities in this app.
*/
public class BaseActivity extends Activity {
private static final String TAG = "BaseActivity";
protected SharedPreferences mPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_onCreate(savedInstanceState);
}
// 因为onCreate方法无法返回状态,因此无法进行状态判断,
// 为了能对上层返回的信息进行判断处理,我们使用_onCreate代替真正的
// onCreate进行工作。onCreate仅在顶层调用_onCreate。
protected boolean _onCreate(Bundle savedInstanceState) {
if (TwitterApplication.mPref.getBoolean(
Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
if (!checkIsLogedIn()) {
return false;
} else {
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
mPreferences = TwitterApplication.mPref; // PreferenceManager.getDefaultSharedPreferences(this);
return true;
}
}
protected void handleLoggedOut() {
if (isTaskRoot()) {
showLogin();
} else {
setResult(RESULT_LOGOUT);
}
finish();
}
public TwitterDatabase getDb() {
return TwitterApplication.mDb;
}
public Weibo getApi() {
return TwitterApplication.mApi;
}
public SharedPreferences getPreferences() {
return mPreferences;
}
@Override
protected void onDestroy() {
super.onDestroy();
}
protected boolean isLoggedIn() {
return getApi().isLoggedIn();
}
private static final int RESULT_LOGOUT = RESULT_FIRST_USER + 1;
// Retrieve interface
// public ImageManager getImageManager() {
// return TwitterApplication.mImageManager;
// }
private void _logout() {
TwitterService.unschedule(BaseActivity.this);
getDb().clearData();
getApi().reset();
// Clear SharedPreferences
SharedPreferences.Editor editor = mPreferences.edit();
editor.clear();
editor.commit();
// TODO: 提供用户手动情况所有缓存选项
TwitterApplication.mImageLoader.getImageManager().clear();
// TODO: cancel notifications.
TwitterService.unschedule(BaseActivity.this);
handleLoggedOut();
}
public void logout() {
Dialog dialog = new AlertDialog.Builder(BaseActivity.this)
.setTitle("提示").setMessage("确实要注销吗?")
.setPositiveButton("确定", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
_logout();
}
}).setNegativeButton("取消", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create();
dialog.show();
}
protected void showLogin() {
Intent intent = new Intent(this, LoginActivity.class);
// TODO: might be a hack?
intent.putExtra(Intent.EXTRA_INTENT, getIntent());
startActivity(intent);
}
protected void manageUpdateChecks() {
//检查后台更新状态设置
boolean isUpdateEnabled = mPreferences.getBoolean(
Preferences.CHECK_UPDATES_KEY, false);
if (isUpdateEnabled) {
TwitterService.schedule(this);
} else if (!TwitterService.isWidgetEnabled()) {
TwitterService.unschedule(this);
}
//检查强制竖屏设置
boolean isOrientationPortrait = mPreferences.getBoolean(
Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false);
if (isOrientationPortrait) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}
// Menus.
protected static final int OPTIONS_MENU_ID_LOGOUT = 1;
protected static final int OPTIONS_MENU_ID_PREFERENCES = 2;
protected static final int OPTIONS_MENU_ID_ABOUT = 3;
protected static final int OPTIONS_MENU_ID_SEARCH = 4;
protected static final int OPTIONS_MENU_ID_REPLIES = 5;
protected static final int OPTIONS_MENU_ID_DM = 6;
protected static final int OPTIONS_MENU_ID_TWEETS = 7;
protected static final int OPTIONS_MENU_ID_TOGGLE_REPLIES = 8;
protected static final int OPTIONS_MENU_ID_FOLLOW = 9;
protected static final int OPTIONS_MENU_ID_UNFOLLOW = 10;
protected static final int OPTIONS_MENU_ID_IMAGE_CAPTURE = 11;
protected static final int OPTIONS_MENU_ID_PHOTO_LIBRARY = 12;
protected static final int OPTIONS_MENU_ID_EXIT = 13;
/**
* 如果增加了Option Menu常量的数量,则必须重载此方法, 以保证其他人使用常量时不产生重复
*
* @return 最大的Option Menu常量
*/
protected int getLastOptionMenuId() {
return OPTIONS_MENU_ID_EXIT;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// SubMenu submenu =
// menu.addSubMenu(R.string.write_label_insert_picture);
// submenu.setIcon(android.R.drawable.ic_menu_gallery);
//
// submenu.add(0, OPTIONS_MENU_ID_IMAGE_CAPTURE, 0,
// R.string.write_label_take_a_picture);
// submenu.add(0, OPTIONS_MENU_ID_PHOTO_LIBRARY, 0,
// R.string.write_label_choose_a_picture);
//
// MenuItem item = menu.add(0, OPTIONS_MENU_ID_SEARCH, 0,
// R.string.omenu_search);
// item.setIcon(android.R.drawable.ic_search_category_default);
// item.setAlphabeticShortcut(SearchManager.MENU_KEY);
MenuItem item;
item = menu.add(0, OPTIONS_MENU_ID_PREFERENCES, 0,
R.string.omenu_settings);
item.setIcon(android.R.drawable.ic_menu_preferences);
item = menu.add(0, OPTIONS_MENU_ID_LOGOUT, 0, R.string.omenu_signout);
item.setIcon(android.R.drawable.ic_menu_revert);
item = menu.add(0, OPTIONS_MENU_ID_ABOUT, 0, R.string.omenu_about);
item.setIcon(android.R.drawable.ic_menu_info_details);
item = menu.add(0, OPTIONS_MENU_ID_EXIT, 0, R.string.omenu_exit);
item.setIcon(android.R.drawable.ic_menu_rotate);
return true;
}
protected static final int REQUEST_CODE_LAUNCH_ACTIVITY = 0;
protected static final int REQUEST_CODE_PREFERENCES = 1;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case OPTIONS_MENU_ID_LOGOUT:
logout();
return true;
case OPTIONS_MENU_ID_SEARCH:
onSearchRequested();
return true;
case OPTIONS_MENU_ID_PREFERENCES:
Intent launchPreferencesIntent = new Intent().setClass(this,
PreferencesActivity.class);
startActivityForResult(launchPreferencesIntent,
REQUEST_CODE_PREFERENCES);
return true;
case OPTIONS_MENU_ID_ABOUT:
//AboutDialog.show(this);
Intent intent = new Intent().setClass(this, AboutActivity.class);
startActivity(intent);
return true;
case OPTIONS_MENU_ID_EXIT:
exit();
return true;
}
return super.onOptionsItemSelected(item);
}
protected void exit() {
TwitterService.unschedule(this);
Intent i = new Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
}
protected void launchActivity(Intent intent) {
// TODO: probably don't need this result chaining to finish upon logout.
// since the subclasses have to check in onResume.
startActivityForResult(intent, REQUEST_CODE_LAUNCH_ACTIVITY);
}
protected void launchDefaultActivity() {
Intent intent = new Intent();
intent.setClass(this, TwitterActivity.class);
startActivity(intent);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_PREFERENCES && resultCode == RESULT_OK) {
manageUpdateChecks();
} else if (requestCode == REQUEST_CODE_LAUNCH_ACTIVITY
&& resultCode == RESULT_LOGOUT) {
Log.d(TAG, "Result logout.");
handleLoggedOut();
}
}
protected boolean checkIsLogedIn() {
if (!getApi().isLoggedIn()) {
Log.d(TAG, "Not logged in.");
handleLoggedOut();
return false;
}
return true;
}
public static boolean isTrue(Bundle bundle, String key) {
return bundle != null && bundle.containsKey(key)
&& bundle.getBoolean(key);
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.base;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.SearchActivity;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.WriteActivity;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.MenuDialog;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
/**
* @deprecated 使用 {@link NavBar} 代替
*/
public class WithHeaderActivity extends BaseActivity {
private static final String TAG = "WithHeaderActivity";
public static final int HEADER_STYLE_HOME = 1;
public static final int HEADER_STYLE_WRITE = 2;
public static final int HEADER_STYLE_BACK = 3;
public static final int HEADER_STYLE_SEARCH = 4;
protected ImageView refreshButton;
protected ImageButton searchButton;
protected ImageButton writeButton;
protected TextView titleButton;
protected Button backButton;
protected ImageButton homeButton;
protected MenuDialog dialog;
protected EditText searchEdit;
protected Feedback mFeedback;
// FIXME: 刷新动画二选一, DELETE ME
protected AnimationDrawable mRefreshAnimation;
protected ProgressBar mProgress = null;
protected ProgressBar mLoadingProgress = null;
//搜索硬按键行为
@Override
public boolean onSearchRequested() {
Intent intent = new Intent();
intent.setClass(this, SearchActivity.class);
startActivity(intent);
return true;
}
// LOGO按钮
protected void addTitleButton() {
titleButton = (TextView) findViewById(R.id.title);
titleButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int top = titleButton.getTop();
int height = titleButton.getHeight();
int x = top + height;
if (null == dialog) {
Log.d(TAG, "Create menu dialog.");
dialog = new MenuDialog(WithHeaderActivity.this);
dialog.bindEvent(WithHeaderActivity.this);
dialog.setPosition(-1, x);
}
// toggle dialog
if (dialog.isShowing()) {
dialog.dismiss(); //没机会触发
} else {
dialog.show();
}
}
});
}
protected void setHeaderTitle(String title) {
titleButton.setBackgroundDrawable( new BitmapDrawable());
titleButton.setText(title);
LayoutParams lp = new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT,android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
lp.setMargins(3, 12, 0, 0);
titleButton.setLayoutParams(lp);
// 中文粗体
TextPaint tp = titleButton.getPaint();
tp.setFakeBoldText(true);
}
protected void setHeaderTitle(int resource) {
titleButton.setBackgroundResource(resource);
}
// 刷新
protected void addRefreshButton() {
final Activity that = this;
refreshButton = (ImageView) findViewById(R.id.top_refresh);
// FIXME: 暂时取消旋转效果, 测试ProgressBar
//refreshButton.setBackgroundResource(R.drawable.top_refresh);
//mRefreshAnimation = (AnimationDrawable) refreshButton.getBackground();
// FIXME: DELETE ME
mProgress = (ProgressBar) findViewById(R.id.progress_bar);
mLoadingProgress = (ProgressBar) findViewById(R.id.top_refresh_progressBar);
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
refreshButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (that instanceof Refreshable) {
((Refreshable) that).doRetrieve();
} else {
Log.e(TAG, "The current view " + that.getClass().getName() + " cann't be retrieved");
}
}
});
}
/**
* @param v
* @deprecated use {@link WithHeaderActivity#setRefreshAnimation(boolean)}
*/
protected void animRotate(View v) {
setRefreshAnimation(true);
}
/**
* @param progress 0~100
* @deprecated use feedback
*/
public void setGlobalProgress(int progress) {
if ( null != mProgress) {
mProgress.setProgress(progress);
}
}
/**
* Start/Stop Top Refresh Button's Animation
*
* @param animate start or stop
* @deprecated use feedback
*/
public void setRefreshAnimation(boolean animate) {
if (mRefreshAnimation != null) {
if (animate) {
mRefreshAnimation.start();
} else {
mRefreshAnimation.setVisible(true, true); // restart
mRefreshAnimation.start(); // goTo frame 0
mRefreshAnimation.stop();
}
} else {
Log.w(TAG, "mRefreshAnimation is null");
}
}
// 搜索
protected void addSearchButton() {
searchButton = (ImageButton) findViewById(R.id.search);
searchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// // 旋转动画
// Animation anim = AnimationUtils.loadAnimation(v.getContext(),
// R.anim.scale_lite);
// v.startAnimation(anim);
//go to SearchActivity
startSearch();
}
});
}
// 这个方法会在SearchActivity里重写
protected boolean startSearch() {
Intent intent = new Intent();
intent.setClass(this, SearchActivity.class);
startActivity(intent);
return true;
}
//搜索框
protected void addSearchBox() {
searchEdit = (EditText) findViewById(R.id.search_edit);
}
// 撰写
protected void addWriteButton() {
writeButton = (ImageButton) findViewById(R.id.writeMessage);
writeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// 动画
Animation anim = AnimationUtils.loadAnimation(v.getContext(),
R.anim.scale_lite);
v.startAnimation(anim);
// forward to write activity
Intent intent = new Intent();
intent.setClass(v.getContext(), WriteActivity.class);
v.getContext().startActivity(intent);
}
});
}
// 回首页
protected void addHomeButton() {
homeButton = (ImageButton) findViewById(R.id.home);
homeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// 动画
Animation anim = AnimationUtils.loadAnimation(v.getContext(),
R.anim.scale_lite);
v.startAnimation(anim);
// forward to TwitterActivity
Intent intent = new Intent();
intent.setClass(v.getContext(), TwitterActivity.class);
v.getContext().startActivity(intent);
}
});
}
// 返回
protected void addBackButton() {
backButton = (Button) findViewById(R.id.top_back);
// 中文粗体
// TextPaint tp = backButton.getPaint();
// tp.setFakeBoldText(true);
backButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Go back to previous activity
finish();
}
});
}
protected void initHeader(int style) {
//FIXME: android 1.6似乎不支持addHeaderView中使用的方法
// 来增加header,造成header无法显示和使用。
// 改用在layout xml里include的方法来确保显示
switch (style) {
case HEADER_STYLE_HOME:
//addHeaderView(R.layout.header);
addTitleButton();
addWriteButton();
addSearchButton();
addRefreshButton();
break;
case HEADER_STYLE_BACK:
//addHeaderView(R.layout.header_back);
addBackButton();
addWriteButton();
addSearchButton();
addRefreshButton();
break;
case HEADER_STYLE_WRITE:
//addHeaderView(R.layout.header_write);
addBackButton();
//addHomeButton();
break;
case HEADER_STYLE_SEARCH:
//addHeaderView(R.layout.header_search);
addBackButton();
addSearchBox();
addSearchButton();
break;
}
}
private void addHeaderView(int resource) {
// find content root view
ViewGroup root = (ViewGroup) getWindow().getDecorView();
ViewGroup content = (ViewGroup) root.getChildAt(0);
View header = View.inflate(WithHeaderActivity.this, resource, null);
// LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
content.addView(header, 0);
}
@Override
protected void onDestroy() {
// dismiss dialog before destroy
// to avoid android.view.WindowLeaked Exception
if (dialog != null){
dialog.dismiss();
}
super.onDestroy();
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.base;
public interface Refreshable {
void doRetrieve();
}
| Java |
package com.ch_linghu.fanfoudroid.ui.base;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.DmActivity;
import com.ch_linghu.fanfoudroid.MentionActivity;
import com.ch_linghu.fanfoudroid.ProfileActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.UserTimelineActivity;
import com.ch_linghu.fanfoudroid.WriteActivity;
import com.ch_linghu.fanfoudroid.WriteDmActivity;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.task.TweetCommonTask;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
public abstract class UserListBaseActivity extends BaseActivity implements
Refreshable {
static final String TAG = "TwitterListBaseActivity";
protected TextView mProgressText;
protected NavBar mNavbar;
protected Feedback mFeedback;
protected static final int STATE_ALL = 0;
protected static final String SIS_RUNNING_KEY = "running";
private static final String USER_ID = "userId";
// Tasks.
protected GenericTask mFavTask;
private TaskListener mFavTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "FavoriteTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onFavSuccess();
} else if (result == TaskResult.IO_ERROR) {
onFavFailure();
}
}
};
static final int DIALOG_WRITE_ID = 0;
abstract protected int getLayoutId();
abstract protected ListView getUserList();
abstract protected TweetAdapter getUserAdapter();
abstract protected void setupState();
abstract protected String getActivityTitle();
abstract protected boolean useBasicMenu();
abstract protected User getContextItemUser(int position);
abstract protected void updateTweet(Tweet tweet);
protected abstract String getUserId();// 获得用户id
public static final int CONTENT_PROFILE_ID = Menu.FIRST + 1;
public static final int CONTENT_STATUS_ID = Menu.FIRST + 2;
public static final int CONTENT_DEL_FRIEND = Menu.FIRST + 3;
public static final int CONTENT_ADD_FRIEND = Menu.FIRST + 4;
public static final int CONTENT_SEND_DM = Menu.FIRST + 5;
public static final int CONTENT_SEND_MENTION = Menu.FIRST + 6;
/**
* 如果增加了Context Menu常量的数量,则必须重载此方法, 以保证其他人使用常量时不产生重复
*
* @return 最大的Context Menu常量
*/
// protected int getLastContextMenuId(){
// return CONTEXT_DEL_FAV_ID;
// }
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)) {
setContentView(getLayoutId());
mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this);
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
mPreferences.getInt(Preferences.TWITTER_ACTIVITY_STATE_KEY,
STATE_ALL);
mProgressText = (TextView) findViewById(R.id.progress_text);
setupState();
registerForContextMenu(getUserList());
registerOnClickListener(getUserList());
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
mFavTask.cancel(true);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (useBasicMenu()) {
AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
User user = getContextItemUser(info.position);
if (user == null) {
Log.w(TAG, "Selected item not available.");
return;
}
menu.add(0, CONTENT_PROFILE_ID, 0,
user.screenName + getResources().getString(
R.string.cmenu_user_profile_prefix));
menu.add(0, CONTENT_STATUS_ID, 0, user.screenName
+ getResources().getString(R.string.cmenu_user_status));
menu.add(0, CONTENT_SEND_MENTION, 0,
getResources().getString(R.string.cmenu_user_send_prefix)
+ user.screenName
+ getResources().getString(
R.string.cmenu_user_sendmention_suffix));
menu.add(0, CONTENT_SEND_DM, 0,
getResources().getString(R.string.cmenu_user_send_prefix)
+ user.screenName
+ getResources().getString(
R.string.cmenu_user_senddm_suffix));
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
User user = getContextItemUser(info.position);
if (user == null) {
Log.w(TAG, "Selected item not available.");
return super.onContextItemSelected(item);
}
switch (item.getItemId()) {
case CONTENT_PROFILE_ID:
launchActivity(ProfileActivity.createIntent(user.id));
return true;
case CONTENT_STATUS_ID:
launchActivity(UserTimelineActivity
.createIntent(user.id, user.name));
return true;
case CONTENT_DEL_FRIEND:
delFriend(user.id);
return true;
case CONTENT_ADD_FRIEND:
addFriend(user.id);
return true;
case CONTENT_SEND_MENTION:
launchActivity(WriteActivity.createNewTweetIntent(String.format(
"@%s ", user.screenName)));
return true;
case CONTENT_SEND_DM:
launchActivity(WriteDmActivity.createIntent(user.id));
return true;
default:
return super.onContextItemSelected(item);
}
}
/**
* 取消关注
*
* @param id
*/
private void delFriend(final String id) {
Builder diaBuilder = new AlertDialog.Builder(UserListBaseActivity.this)
.setTitle("关注提示").setMessage("确实要取消关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (cancelFollowingTask != null
&& cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
cancelFollowingTask = new CancelFollowingTask();
cancelFollowingTask
.setListener(cancelFollowingTaskLinstener);
TaskParams params = new TaskParams();
params.put(USER_ID, id);
cancelFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
private GenericTask cancelFollowingTask;
/**
* 取消关注
*
* @author Dino
*
*/
private class CancelFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
// TODO:userid
String userId = params[0].getString(USER_ID);
getApi().destroyFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener cancelFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
// followingBtn.setText("添加关注");
// isFollowingText.setText(getResources().getString(
// R.string.profile_notfollowing));
// followingBtn.setOnClickListener(setfollowingListener);
Toast.makeText(getBaseContext(), "取消关注成功", Toast.LENGTH_SHORT)
.show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(getBaseContext(), "取消关注失败", Toast.LENGTH_SHORT)
.show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
private GenericTask setFollowingTask;
/**
* 设置关注
*
* @param id
*/
private void addFriend(String id) {
Builder diaBuilder = new AlertDialog.Builder(UserListBaseActivity.this)
.setTitle("关注提示").setMessage("确实要添加关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (setFollowingTask != null
&& setFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
setFollowingTask = new SetFollowingTask();
setFollowingTask
.setListener(setFollowingTaskLinstener);
TaskParams params = new TaskParams();
setFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
/**
* 设置关注
*
* @author Dino
*
*/
private class SetFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
String userId = params[0].getString(USER_ID);
getApi().createFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener setFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
// followingBtn.setText("取消关注");
// isFollowingText.setText(getResources().getString(
// R.string.profile_isfollowing));
// followingBtn.setOnClickListener(cancelFollowingListener);
Toast.makeText(getBaseContext(), "关注成功", Toast.LENGTH_SHORT)
.show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(getBaseContext(), "关注失败", Toast.LENGTH_SHORT)
.show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case OPTIONS_MENU_ID_TWEETS:
launchActivity(TwitterActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_REPLIES:
launchActivity(MentionActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_DM:
launchActivity(DmActivity.createIntent());
return true;
}
return super.onOptionsItemSelected(item);
}
private void draw() {
getUserAdapter().refresh();
}
private void goTop() {
getUserList().setSelection(0);
}
protected void adapterRefresh() {
getUserAdapter().refresh();
}
// for HasFavorite interface
public void doFavorite(String action, String id) {
if (!TextUtils.isEmpty(id)) {
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mFavTask = new TweetCommonTask.FavoriteTask(this);
mFavTask.setFeedback(mFeedback);
mFavTask.setListener(mFavTaskListener);
TaskParams params = new TaskParams();
params.put("action", action);
params.put("id", id);
mFavTask.execute(params);
}
}
}
public void onFavSuccess() {
// updateProgress(getString(R.string.refreshing));
adapterRefresh();
}
public void onFavFailure() {
// updateProgress(getString(R.string.refreshing));
}
protected void specialItemClicked(int position) {
}
/*
* TODO:单击列表项
*/
protected void registerOnClickListener(ListView listView) {
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Toast.makeText(getBaseContext(), "选择第"+position+"个列表",Toast.LENGTH_SHORT).show();
User user = getContextItemUser(position);
if (user == null) {
Log.w(TAG, "selected item not available");
specialItemClicked(position);
} else {
launchActivity(ProfileActivity.createIntent(user.id));
}
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.base;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskManager;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter;
public abstract class UserArrayBaseActivity extends UserListBaseActivity {
static final String TAG = "UserArrayBaseActivity";
// Views.
protected ListView mUserList;
protected UserArrayAdapter mUserListAdapter;
protected TextView loadMoreBtn;
protected ProgressBar loadMoreGIF;
protected TextView loadMoreBtnTop;
protected ProgressBar loadMoreGIFTop;
protected static int lastPosition = 0;
// Tasks.
protected TaskManager taskManager = new TaskManager();
private GenericTask mRetrieveTask;
private GenericTask mFollowersRetrieveTask;
private GenericTask mGetMoreTask;// 每次100用户
public abstract Paging getCurrentPage();// 加载
public abstract Paging getNextPage();// 加载
// protected abstract String[] getIds();
protected abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers(
String userId, Paging page) throws HttpException;
private ArrayList<com.ch_linghu.fanfoudroid.data.User> allUserList;
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)) {
doRetrieve();// 加载第一页
return true;
} else {
return false;
}
}
@Override
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new RetrieveTask();
mRetrieveTask.setFeedback(mFeedback);
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute();
// Add Task to manager
taskManager.addTask(mRetrieveTask);
}
}
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "RetrieveTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
draw();
}
updateProgress("");
}
@Override
public void onPreExecute(GenericTask task) {
onRetrieveBegin();
}
@Override
public void onProgressUpdate(GenericTask task, Object param) {
Log.d(TAG, "onProgressUpdate");
draw();
}
};
public void updateProgress(String progress) {
mProgressText.setText(progress);
}
public void onRetrieveBegin() {
updateProgress(getString(R.string.page_status_refreshing));
}
/**
* TODO:从API获取当前Followers
*
* @author Dino
*
*/
private class RetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
Log.d(TAG, "load RetrieveTask");
List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null;
try {
usersList = getUsers(getUserId(), getCurrentPage());
} catch (HttpException e) {
e.printStackTrace();
return TaskResult.IO_ERROR;
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList));
for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
allUserList.add(User.create(user));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
return TaskResult.OK;
}
}
@Override
protected int getLayoutId() {
return R.layout.follower;
}
@Override
protected void setupState() {
setTitle(getActivityTitle());
mUserList = (ListView) findViewById(R.id.follower_list);
setupListHeader(true);
mUserListAdapter = new UserArrayAdapter(this);
mUserList.setAdapter(mUserListAdapter);
allUserList = new ArrayList<com.ch_linghu.fanfoudroid.data.User>();
}
@Override
protected String getActivityTitle() {
// TODO Auto-generated method stub
return null;
}
@Override
protected boolean useBasicMenu() {
return true;
}
@Override
protected User getContextItemUser(int position) {
// position = position - 1;
// 加入footer跳过footer
if (position < mUserListAdapter.getCount()) {
User item = (User) mUserListAdapter.getItem(position);
if (item == null) {
return null;
} else {
return item;
}
} else {
return null;
}
}
/**
* TODO:不知道啥用
*/
@Override
protected void updateTweet(Tweet tweet) {
// TODO Auto-generated method stub
}
@Override
protected ListView getUserList() {
return mUserList;
}
@Override
protected TweetAdapter getUserAdapter() {
return mUserListAdapter;
}
/**
* 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用
*/
protected void setupListHeader(boolean addFooter) {
// Add footer to Listview
View footer = View.inflate(this, R.layout.listview_footer, null);
mUserList.addFooterView(footer, null, true);
// Find View
loadMoreBtn = (TextView) findViewById(R.id.ask_for_more);
loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar);
}
@Override
protected void specialItemClicked(int position) {
if (position == mUserList.getCount() - 1) {
// footer
loadMoreGIF.setVisibility(View.VISIBLE);
doGetMore();
}
}
public void doGetMore() {
Log.d(TAG, "Attempting getMore.");
mFeedback.start("");
if (mGetMoreTask != null
&& mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mGetMoreTask = new GetMoreTask();
mGetMoreTask.setListener(getMoreListener);
mGetMoreTask.execute();
// Add Task to manager
taskManager.addTask(mGetMoreTask);
}
}
private TaskListener getMoreListener = new TaskAdapter() {
@Override
public String getName() {
return "getMore";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
super.onPostExecute(task, result);
draw();
mFeedback.success("");
loadMoreGIF.setVisibility(View.GONE);
}
};
/**
* TODO:需要重写,获取下一批用户,按页分100页一次
*
* @author Dino
*
*/
private class GetMoreTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
Log.d(TAG, "load RetrieveTask");
List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null;
try {
usersList = getUsers(getUserId(), getNextPage());
mFeedback.update(60);
} catch (HttpException e) {
e.printStackTrace();
return TaskResult.IO_ERROR;
}
// 将获取到的数据(保存/更新)到数据库
getDb().syncWeiboUsers(usersList);
mFeedback.update(100 - (int) Math.floor(usersList.size() * 2));
for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
allUserList.add(User.create(user));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
mFeedback.update(99);
return TaskResult.OK;
}
}
public void draw() {
mUserListAdapter.refresh(allUserList);
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import java.util.ArrayList;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class TweetArrayAdapter extends BaseAdapter implements TweetAdapter {
private static final String TAG = "TweetArrayAdapter";
protected ArrayList<Tweet> mTweets;
private Context mContext;
protected LayoutInflater mInflater;
protected StringBuilder mMetaBuilder;
private ImageLoaderCallback callback = new ImageLoaderCallback(){
@Override
public void refresh(String url, Bitmap bitmap) {
TweetArrayAdapter.this.refresh();
}
};
public TweetArrayAdapter(Context context) {
mTweets = new ArrayList<Tweet>();
mContext = context;
mInflater = LayoutInflater.from(mContext);
mMetaBuilder = new StringBuilder();
}
@Override
public int getCount() {
return mTweets.size();
}
@Override
public Object getItem(int position) {
return mTweets.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
private static class ViewHolder {
public TextView tweetUserText;
public TextView tweetText;
public ImageView profileImage;
public TextView metaText;
public ImageView fav;
public ImageView has_image;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext);
boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true);
if (convertView == null) {
view = mInflater.inflate(R.layout.tweet, parent, false);
ViewHolder holder = new ViewHolder();
holder.tweetUserText = (TextView) view
.findViewById(R.id.tweet_user_text);
holder.tweetText = (TextView) view.findViewById(R.id.tweet_text);
holder.profileImage = (ImageView) view
.findViewById(R.id.profile_image);
holder.metaText = (TextView) view
.findViewById(R.id.tweet_meta_text);
holder.fav = (ImageView) view.findViewById(R.id.tweet_fav);
holder.has_image = (ImageView) view.findViewById(R.id.tweet_has_image);
view.setTag(holder);
} else {
view = convertView;
}
ViewHolder holder = (ViewHolder) view.getTag();
Tweet tweet = mTweets.get(position);
holder.tweetUserText.setText(tweet.screenName);
TextHelper.setSimpleTweetText(holder.tweetText, tweet.text);
// holder.tweetText.setText(tweet.text, BufferType.SPANNABLE);
String profileImageUrl = tweet.profileImageUrl;
if (useProfileImage){
if (!TextUtils.isEmpty(profileImageUrl)) {
holder.profileImage.setImageBitmap(TwitterApplication.mImageLoader
.get(profileImageUrl, callback));
}
}else{
holder.profileImage.setVisibility(View.GONE);
}
holder.metaText.setText(Tweet.buildMetaText(mMetaBuilder,
tweet.createdAt, tweet.source, tweet.inReplyToScreenName));
if (tweet.favorited.equals("true")) {
holder.fav.setVisibility(View.VISIBLE);
} else {
holder.fav.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(tweet.thumbnail_pic)) {
holder.has_image.setVisibility(View.VISIBLE);
} else {
holder.has_image.setVisibility(View.GONE);
}
return view;
}
public void refresh(ArrayList<Tweet> tweets) {
mTweets = tweets;
notifyDataSetChanged();
}
@Override
public void refresh() {
notifyDataSetChanged();
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import android.widget.ListAdapter;
public interface TweetAdapter extends ListAdapter{
void refresh();
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import android.app.Activity;
import android.view.MotionEvent;
import com.ch_linghu.fanfoudroid.BrowseActivity;
import com.ch_linghu.fanfoudroid.MentionActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterActivity;
/**
* MyActivityFlipper 利用左右滑动手势切换Activity
*
* 1. 切换Activity, 继承与 {@link ActivityFlipper} 2. 手势识别, 实现接口
* {@link Widget.OnGestureListener}
*
*/
public class MyActivityFlipper extends ActivityFlipper implements
Widget.OnGestureListener {
public MyActivityFlipper() {
super();
}
public MyActivityFlipper(Activity activity) {
super(activity);
// TODO Auto-generated constructor stub
}
// factory
public static MyActivityFlipper create(Activity activity) {
MyActivityFlipper flipper = new MyActivityFlipper(activity);
flipper.addActivity(BrowseActivity.class);
flipper.addActivity(TwitterActivity.class);
flipper.addActivity(MentionActivity.class);
flipper.setToastResource(new int[] { R.drawable.point_left,
R.drawable.point_center, R.drawable.point_right });
flipper.setInAnimation(R.anim.push_left_in);
flipper.setOutAnimation(R.anim.push_left_out);
flipper.setPreviousInAnimation(R.anim.push_right_in);
flipper.setPreviousOutAnimation(R.anim.push_right_out);
return flipper;
}
@Override
public boolean onFlingDown(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return false; // do nothing
}
@Override
public boolean onFlingUp(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return false; // do nothing
}
@Override
public boolean onFlingLeft(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
autoShowNext();
return true;
}
@Override
public boolean onFlingRight(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
autoShowPrevious();
return true;
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.AbsListView;
import android.widget.ListView;
public class MyListView extends ListView implements ListView.OnScrollListener {
private int mScrollState = OnScrollListener.SCROLL_STATE_IDLE;
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
setOnScrollListener(this);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
boolean result = super.onInterceptTouchEvent(event);
if (mScrollState == OnScrollListener.SCROLL_STATE_FLING) {
return true;
}
return result;
}
private OnNeedMoreListener mOnNeedMoreListener;
public static interface OnNeedMoreListener {
public void needMore();
}
public void setOnNeedMoreListener(OnNeedMoreListener onNeedMoreListener) {
mOnNeedMoreListener = onNeedMoreListener;
}
private int mFirstVisibleItem;
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (mOnNeedMoreListener == null) {
return;
}
if (firstVisibleItem != mFirstVisibleItem) {
if (firstVisibleItem + visibleItemCount >= totalItemCount) {
mOnNeedMoreListener.needMore();
}
} else {
mFirstVisibleItem = firstVisibleItem;
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
mScrollState = scrollState;
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.text.Layout;
import android.text.Spannable;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.URLSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
public class MyTextView extends TextView {
private static float mFontSize = 15;
private static boolean mFontSizeChanged = true;
public MyTextView(Context context) {
super(context, null);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setLinksClickable(false);
Resources res = getResources();
int color = res.getColor(R.color.link_color);
setLinkTextColor(color);
initFontSize();
}
public void initFontSize() {
if ( mFontSizeChanged ) {
mFontSize = getFontSizeFromPreferences(mFontSize);
setFontSizeChanged(false); // reset
}
setTextSize(mFontSize);
}
private float getFontSizeFromPreferences(float defaultValue) {
SharedPreferences preferences = TwitterApplication.mPref;
if (preferences.contains(Preferences.UI_FONT_SIZE)) {
Log.v("DEBUG", preferences.getString(Preferences.UI_FONT_SIZE, "null") + " CHANGE FONT SIZE");
return Float.parseFloat(preferences.getString(
Preferences.UI_FONT_SIZE, "14"));
}
return defaultValue;
}
private URLSpan mCurrentLink;
private ForegroundColorSpan mLinkFocusStyle = new ForegroundColorSpan(
Color.RED);
@Override
public boolean onTouchEvent(MotionEvent event) {
CharSequence text = getText();
int action = event.getAction();
if (!(text instanceof Spannable)) {
return super.onTouchEvent(event);
}
Spannable buffer = (Spannable) text;
if (action == MotionEvent.ACTION_UP
|| action == MotionEvent.ACTION_DOWN
|| action == MotionEvent.ACTION_MOVE) {
TextView widget = this;
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);
if (link.length != 0) {
if (action == MotionEvent.ACTION_UP) {
if (mCurrentLink == link[0]) {
link[0].onClick(widget);
}
mCurrentLink = null;
buffer.removeSpan(mLinkFocusStyle);
} else if (action == MotionEvent.ACTION_DOWN) {
mCurrentLink = link[0];
buffer.setSpan(mLinkFocusStyle,
buffer.getSpanStart(link[0]),
buffer.getSpanEnd(link[0]),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return true;
}
}
mCurrentLink = null;
buffer.removeSpan(mLinkFocusStyle);
return super.onTouchEvent(event);
}
public static void setFontSizeChanged(boolean isChanged) {
mFontSizeChanged = isChanged;
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.util.Log;
public class FeedbackFactory {
private static final String TAG = "FeedbackFactory";
public static enum FeedbackType {
DIALOG, PROGRESS, REFRESH
};
public static Feedback create(Context context, FeedbackType type) {
Feedback feedback = null;
switch (type) {
case PROGRESS:
feedback = new SimpleFeedback(context);
break;
}
if (null == feedback || !feedback.isAvailable()) {
feedback = new FeedbackAdapter(context);
Log.e(TAG, type + " feedback is not available.");
}
return feedback;
}
public static class FeedbackAdapter implements Feedback {
public FeedbackAdapter(Context context) {}
@Override
public void start(CharSequence text) {}
@Override
public void cancel(CharSequence text) {}
@Override
public void success(CharSequence text) {}
@Override
public void failed(CharSequence text) {}
@Override
public void update(Object arg0) {}
@Override
public boolean isAvailable() { return true; }
@Override
public void setIndeterminate(boolean indeterminate) {}
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.R;
public class SimpleFeedback implements Feedback, Widget {
private static final String TAG = "SimpleFeedback";
public static final int MAX = 100;
private ProgressBar mProgress = null;
private ProgressBar mLoadingProgress = null;
public SimpleFeedback(Context context) {
mProgress = (ProgressBar) ((Activity) context)
.findViewById(R.id.progress_bar);
mLoadingProgress = (ProgressBar) ((Activity) context)
.findViewById(R.id.top_refresh_progressBar);
}
@Override
public void start(CharSequence text) {
mProgress.setProgress(20);
mLoadingProgress.setVisibility(View.VISIBLE);
}
@Override
public void success(CharSequence text) {
mProgress.setProgress(100);
mLoadingProgress.setVisibility(View.GONE);
resetProgressBar();
}
@Override
public void failed(CharSequence text) {
resetProgressBar();
showMessage(text);
}
@Override
public void cancel(CharSequence text) {
}
@Override
public void update(Object arg0) {
if (arg0 instanceof Integer) {
mProgress.setProgress((Integer) arg0);
} else if (arg0 instanceof CharSequence) {
showMessage((String) arg0);
}
}
@Override
public void setIndeterminate(boolean indeterminate) {
mProgress.setIndeterminate(indeterminate);
}
@Override
public Context getContext() {
if (mProgress != null) {
return mProgress.getContext();
}
if (mLoadingProgress != null) {
return mLoadingProgress.getContext();
}
return null;
}
@Override
public boolean isAvailable() {
if (null == mProgress) {
Log.e(TAG, "R.id.progress_bar is missing");
return false;
}
if (null == mLoadingProgress) {
Log.e(TAG, "R.id.top_refresh_progressBar is missing");
return false;
}
return true;
}
/**
* @param total 0~100
* @param maxSize max size of list
* @param list
* @return
*/
public static int calProgressBySize(int total, int maxSize, List<?> list) {
if (null != list) {
return (MAX - (int)Math.floor(list.size() * (total/maxSize)));
}
return MAX;
}
private void resetProgressBar() {
if (mProgress.isIndeterminate()) {
//TODO: 第二次不会出现
mProgress.setIndeterminate(false);
}
mProgress.setProgress(0);
}
private void showMessage(CharSequence text) {
Toast.makeText(getContext(), text, Toast.LENGTH_LONG).show();
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.fanfou.Weibo;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
//TODO:
/*
* 用于用户的Adapter
*/
public class UserArrayAdapter extends BaseAdapter implements TweetAdapter{
private static final String TAG = "UserArrayAdapter";
private static final String USER_ID="userId";
protected ArrayList<User> mUsers;
private Context mContext;
protected LayoutInflater mInflater;
public UserArrayAdapter(Context context) {
mUsers = new ArrayList<User>();
mContext = context;
mInflater = LayoutInflater.from(mContext);
}
@Override
public int getCount() {
return mUsers.size();
}
@Override
public Object getItem(int position) {
return mUsers.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
private static class ViewHolder {
public ImageView profileImage;
public TextView screenName;
public TextView userId;
public TextView lastStatus;
public TextView followBtn;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext);
boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true);
if (convertView == null) {
view = mInflater.inflate(R.layout.follower_item, parent, false);
ViewHolder holder = new ViewHolder();
holder.profileImage = (ImageView) view.findViewById(R.id.profile_image);
holder.screenName = (TextView) view.findViewById(R.id.screen_name);
holder.userId = (TextView) view.findViewById(R.id.user_id);
//holder.lastStatus = (TextView) view.findViewById(R.id.last_status);
holder.followBtn = (TextView) view.findViewById(R.id.follow_btn);
view.setTag(holder);
} else {
view = convertView;
}
ViewHolder holder = (ViewHolder) view.getTag();
final User user = mUsers.get(position);
String profileImageUrl = user.profileImageUrl;
if (useProfileImage){
if (!TextUtils.isEmpty(profileImageUrl)) {
holder.profileImage.setImageBitmap(TwitterApplication.mImageLoader
.get(profileImageUrl, callback));
}
}else{
holder.profileImage.setVisibility(View.GONE);
}
//holder.profileImage.setImageBitmap(ImageManager.mDefaultBitmap);
holder.screenName.setText(user.screenName);
holder.userId.setText(user.id);
//holder.lastStatus.setText(user.lastStatus);
holder.followBtn.setText(user.isFollowing ? mContext
.getString(R.string.general_del_friend) : mContext
.getString(R.string.general_add_friend));
holder.followBtn.setOnClickListener(user.isFollowing?new OnClickListener(){
@Override
public void onClick(View v) {
//Toast.makeText(mContext, user.name+"following", Toast.LENGTH_SHORT).show();
delFriend(user.id);
}}:new OnClickListener(){
@Override
public void onClick(View v) {
//Toast.makeText(mContext, user.name+"not following", Toast.LENGTH_SHORT).show();
addFriend(user.id);
}});
return view;
}
public void refresh(ArrayList<User> users) {
mUsers = users;
notifyDataSetChanged();
}
@Override
public void refresh() {
notifyDataSetChanged();
}
private ImageLoaderCallback callback = new ImageLoaderCallback(){
@Override
public void refresh(String url, Bitmap bitmap) {
UserArrayAdapter.this.refresh();
}
};
/**
* 取消关注
* @param id
*/
private void delFriend(final String id) {
Builder diaBuilder = new AlertDialog.Builder(mContext)
.setTitle("关注提示").setMessage("确实要取消关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (cancelFollowingTask != null
&& cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
cancelFollowingTask = new CancelFollowingTask();
cancelFollowingTask
.setListener(cancelFollowingTaskLinstener);
TaskParams params = new TaskParams();
params.put(USER_ID, id);
cancelFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
private GenericTask cancelFollowingTask;
/**
* 取消关注
*
* @author Dino
*
*/
private class CancelFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
//TODO:userid
String userId=params[0].getString(USER_ID);
getApi().destroyFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener cancelFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
// followingBtn.setText("添加关注");
// isFollowingText.setText(getResources().getString(
// R.string.profile_notfollowing));
// followingBtn.setOnClickListener(setfollowingListener);
Toast.makeText(mContext, "取消关注成功", Toast.LENGTH_SHORT).show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(mContext, "取消关注失败", Toast.LENGTH_SHORT).show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
private GenericTask setFollowingTask;
/**
* 设置关注
* @param id
*/
private void addFriend(String id){
Builder diaBuilder = new AlertDialog.Builder(mContext)
.setTitle("关注提示").setMessage("确实要添加关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (setFollowingTask != null
&& setFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
setFollowingTask = new SetFollowingTask();
setFollowingTask
.setListener(setFollowingTaskLinstener);
TaskParams params = new TaskParams();
setFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
/**
* 设置关注
*
* @author Dino
*
*/
private class SetFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
String userId=params[0].getString(USER_ID);
getApi().createFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener setFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
// followingBtn.setText("取消关注");
// isFollowingText.setText(getResources().getString(
// R.string.profile_isfollowing));
// followingBtn.setOnClickListener(cancelFollowingListener);
Toast.makeText(mContext, "关注成功", Toast.LENGTH_SHORT).show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(mContext, "关注失败", Toast.LENGTH_SHORT).show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
public Weibo getApi() {
return TwitterApplication.mApi;
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
public interface IFlipper {
void showNext();
void showPrevious();
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
public interface Widget {
Context getContext();
// TEMP
public static interface OnGestureListener {
/**
* @param e1
* The first down motion event that started the fling.
* @param e2
* The move motion event that triggered the current onFling.
* @param velocityX
* The velocity of this fling measured in pixels per second
* along the x axis.
* @param velocityY
* The velocity of this fling measured in pixels per second
* along the y axis.
* @return true if the event is consumed, else false
*
* @see SimpleOnGestureListener#onFling
*/
boolean onFlingDown(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY);
boolean onFlingUp(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY);
boolean onFlingLeft(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY);
boolean onFlingRight(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY);
}
public static interface OnRefreshListener {
void onRefresh();
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.SearchActivity;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.WriteActivity;
import com.ch_linghu.fanfoudroid.ui.base.Refreshable;
public class NavBar implements Widget {
private static final String TAG = "NavBar";
public static final int HEADER_STYLE_HOME = 1;
public static final int HEADER_STYLE_WRITE = 2;
public static final int HEADER_STYLE_BACK = 3;
public static final int HEADER_STYLE_SEARCH = 4;
private ImageView mRefreshButton;
private ImageButton mSearchButton;
private ImageButton mWriteButton;
private TextView mTitleButton;
private Button mBackButton;
private ImageButton mHomeButton;
private MenuDialog mDialog;
private EditText mSearchEdit;
/** @deprecated 已废弃 */
protected AnimationDrawable mRefreshAnimation;
private ProgressBar mProgressBar = null; // 进度条(横)
private ProgressBar mLoadingProgress = null; // 旋转图标
public NavBar(int style, Context context) {
initHeader(style, (Activity) context);
}
private void initHeader(int style, final Activity activity) {
switch (style) {
case HEADER_STYLE_HOME:
addTitleButtonTo(activity);
addWriteButtonTo(activity);
addSearchButtonTo(activity);
addRefreshButtonTo(activity);
break;
case HEADER_STYLE_BACK:
addBackButtonTo(activity);
addWriteButtonTo(activity);
addSearchButtonTo(activity);
addRefreshButtonTo(activity);
break;
case HEADER_STYLE_WRITE:
addBackButtonTo(activity);
break;
case HEADER_STYLE_SEARCH:
addBackButtonTo(activity);
addSearchBoxTo(activity);
addSearchButtonTo(activity);
break;
}
}
/**
* 搜索硬按键行为
* @deprecated 这个不晓得还有没有用, 已经是已经被新的搜索替代的吧 ?
*/
public boolean onSearchRequested() {
/*
Intent intent = new Intent();
intent.setClass(this, SearchActivity.class);
startActivity(intent);
*/
return true;
}
/**
* 添加[LOGO/标题]按钮
* @param acticity
*/
private void addTitleButtonTo(final Activity acticity) {
mTitleButton = (TextView) acticity.findViewById(R.id.title);
mTitleButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int top = mTitleButton.getTop();
int height = mTitleButton.getHeight();
int x = top + height;
if (null == mDialog) {
Log.d(TAG, "Create menu dialog.");
mDialog = new MenuDialog(acticity);
mDialog.bindEvent(acticity);
mDialog.setPosition(-1, x);
}
// toggle dialog
if (mDialog.isShowing()) {
mDialog.dismiss(); // 没机会触发
} else {
mDialog.show();
}
}
});
}
/**
* 设置标题
* @param title
*/
public void setHeaderTitle(String title) {
if (null != mTitleButton) {
mTitleButton.setText(title);
TextPaint tp = mTitleButton.getPaint();
tp.setFakeBoldText(true); // 中文粗体
}
}
/**
* 设置标题
* @param resource R.string.xxx
*/
public void setHeaderTitle(int resource) {
if (null != mTitleButton) {
mTitleButton.setBackgroundResource(resource);
}
}
/**
* 添加[刷新]按钮
* @param activity
*/
private void addRefreshButtonTo(final Activity activity) {
mRefreshButton = (ImageView) activity.findViewById(R.id.top_refresh);
// FIXME: DELETE ME 暂时取消旋转效果, 测试ProgressBar
// refreshButton.setBackgroundResource(R.drawable.top_refresh);
// mRefreshAnimation = (AnimationDrawable)
// refreshButton.getBackground();
mProgressBar = (ProgressBar) activity.findViewById(R.id.progress_bar);
mLoadingProgress = (ProgressBar) activity
.findViewById(R.id.top_refresh_progressBar);
mRefreshButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (activity instanceof Refreshable) {
((Refreshable) activity).doRetrieve();
} else {
Log.e(TAG, "The current view "
+ activity.getClass().getName()
+ " cann't be retrieved");
}
}
});
}
/**
* Start/Stop Top Refresh Button's Animation
*
* @param animate
* start or stop
* @deprecated use feedback
*/
public void setRefreshAnimation(boolean animate) {
if (mRefreshAnimation != null) {
if (animate) {
mRefreshAnimation.start();
} else {
mRefreshAnimation.setVisible(true, true); // restart
mRefreshAnimation.start(); // goTo frame 0
mRefreshAnimation.stop();
}
} else {
Log.w(TAG, "mRefreshAnimation is null");
}
}
/**
* 添加[搜索]按钮
* @param activity
*/
private void addSearchButtonTo(final Activity activity) {
mSearchButton = (ImageButton) activity.findViewById(R.id.search);
mSearchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startSearch(activity);
}
});
}
// 这个方法会在SearchActivity里重写
protected boolean startSearch(final Activity activity) {
Intent intent = new Intent();
intent.setClass(activity, SearchActivity.class);
activity.startActivity(intent);
return true;
}
/**
* 添加[搜索框]
* @param activity
*/
private void addSearchBoxTo(final Activity activity) {
mSearchEdit = (EditText) activity.findViewById(R.id.search_edit);
}
/**
* 添加[撰写]按钮
* @param activity
*/
private void addWriteButtonTo(final Activity activity) {
mWriteButton = (ImageButton) activity.findViewById(R.id.writeMessage);
mWriteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// forward to write activity
Intent intent = new Intent();
intent.setClass(v.getContext(), WriteActivity.class);
v.getContext().startActivity(intent);
}
});
}
/**
* 添加[回首页]按钮
* @param activity
*/
@SuppressWarnings("unused")
private void addHomeButton(final Activity activity) {
mHomeButton = (ImageButton) activity.findViewById(R.id.home);
mHomeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// 动画
Animation anim = AnimationUtils.loadAnimation(v.getContext(),
R.anim.scale_lite);
v.startAnimation(anim);
// forward to TwitterActivity
Intent intent = new Intent();
intent.setClass(v.getContext(), TwitterActivity.class);
v.getContext().startActivity(intent);
}
});
}
/**
* 添加[返回]按钮
* @param activity
*/
private void addBackButtonTo(final Activity activity) {
mBackButton = (Button) activity.findViewById(R.id.top_back);
// 中文粗体
// TextPaint tp = backButton.getPaint();
// tp.setFakeBoldText(true);
mBackButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Go back to previous activity
activity.finish();
}
});
}
public void destroy() {
// dismiss dialog before destroy
// to avoid android.view.WindowLeaked Exception
if (mDialog != null) {
mDialog.dismiss();
mDialog = null;
}
mRefreshButton = null;
mSearchButton = null;
mWriteButton = null;
mTitleButton = null;
mBackButton = null;
mHomeButton = null;
mSearchButton = null;
mSearchEdit = null;
mProgressBar = null;
mLoadingProgress = null;
}
public ImageView getRefreshButton() {
return mRefreshButton;
}
public ImageButton getSearchButton() {
return mSearchButton;
}
public ImageButton getWriteButton() {
return mWriteButton;
}
public TextView getTitleButton() {
return mTitleButton;
}
public Button getBackButton() {
return mBackButton;
}
public ImageButton getHomeButton() {
return mHomeButton;
}
public MenuDialog getDialog() {
return mDialog;
}
public EditText getSearchEdit() {
return mSearchEdit;
}
/** @deprecated 已废弃 */
public AnimationDrawable getRefreshAnimation() {
return mRefreshAnimation;
}
public ProgressBar getProgressBar() {
return mProgressBar;
}
public ProgressBar getLoadingProgress() {
return mLoadingProgress;
}
@Override
public Context getContext() {
if (null != mDialog) {
return mDialog.getContext();
}
if (null != mTitleButton) {
return mTitleButton.getContext();
}
return null;
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;
import com.ch_linghu.fanfoudroid.R;
/**
* ActivityFlipper, 和 {@link ViewFactory} 类似, 只是设计用于切换activity.
*
* 切换的前后顺序取决与注册时的先后顺序
*
* USAGE: <code>
* ActivityFlipper mFlipper = new ActivityFlipper(this);
* mFlipper.addActivity(TwitterActivity.class);
* mFlipper.addActivity(MentionActivity.class);
* mFlipper.addActivity(DmActivity.class);
*
* // switch activity
* mFlipper.setCurrentActivity(TwitterActivity.class);
* mFlipper.showNext();
* mFlipper.showPrevious();
*
* // or without set current activity
* mFlipper.showNextOf(TwitterActivity.class);
* mFlipper.showPreviousOf(TwitterActivity.class);
*
* // or auto mode, use the context as current activity
* mFlipper.autoShowNext();
* mFlipper.autoShowPrevious();
*
* // set toast
* mFlipper.setToastResource(new int[] {
* R.drawable.point_left,
* R.drawable.point_center,
* R.drawable.point_right
* });
*
* // set Animation
* mFlipper.setInAnimation(R.anim.push_left_in);
* mFlipper.setOutAnimation(R.anim.push_left_out);
* mFlipper.setPreviousInAnimation(R.anim.push_right_in);
* mFlipper.setPreviousOutAnimation(R.anim.push_right_out);
* </code>
*
*/
public class ActivityFlipper implements IFlipper {
private static final String TAG = "ActivityFlipper";
private static final int SHOW_NEXT = 0;
private static final int SHOW_PROVIOUS = 1;
private int mDirection = SHOW_NEXT;
private boolean mToastEnabled = false;
private int[] mToastResourcesMap = new int[]{};
private boolean mAnimationEnabled = false;
private int mNextInAnimation = -1;
private int mNextOutAnimation = -1;
private int mPreviousInAnimation = -1;
private int mPreviousOutAnimation = -1;
private Activity mActivity;
private List<Class<?>> mActivities = new ArrayList<Class<?>>();;
private int mWhichActivity = 0;
public ActivityFlipper() {
}
public ActivityFlipper(Activity activity) {
mActivity = activity;
}
/**
* Launch Activity
*
* @param cls
* class of activity
*/
public void launchActivity(Class<?> cls) {
Log.v(TAG, "launch activity :" + cls.getName());
Intent intent = new Intent();
intent.setClass(mActivity, cls);
mActivity.startActivity(intent);
}
public void setToastResource(int[] resourceIds) {
mToastEnabled = true;
mToastResourcesMap = resourceIds;
}
private void maybeShowToast(int whichActicity) {
if (mToastEnabled && whichActicity < mToastResourcesMap.length) {
final Toast myToast = new Toast(mActivity);
final ImageView myView = new ImageView(mActivity);
myView.setImageResource(mToastResourcesMap[whichActicity]);
myToast.setView(myView);
myToast.setDuration(Toast.LENGTH_SHORT);
myToast.setGravity(Gravity.BOTTOM | Gravity.CENTER, 0, 0);
myToast.show();
}
}
private void maybeShowAnimation(int whichActivity) {
if (mAnimationEnabled) {
boolean showPrevious = (mDirection == SHOW_PROVIOUS);
if (showPrevious && mPreviousInAnimation != -1
&& mPreviousOutAnimation != -1) {
mActivity.overridePendingTransition(
mPreviousInAnimation, mPreviousOutAnimation);
return; // use Previous Animation
}
if (mNextInAnimation != -1 && mNextOutAnimation != -1) {
mActivity.overridePendingTransition(
mNextInAnimation, mNextOutAnimation);
}
}
}
/**
* Launch Activity by index
*
* @param whichActivity
* the index of Activity
*/
private void launchActivity(int whichActivity) {
launchActivity(mActivities.get(whichActivity));
maybeShowToast(whichActivity);
maybeShowAnimation(whichActivity);
}
/**
* Add Activity NOTE: 添加的顺序很重要
*
* @param cls
* class of activity
*/
public void addActivity(Class<?> cls) {
mActivities.add(cls);
}
/**
* Get index of the Activity
*
* @param cls
* class of activity
* @return
*/
private int getIndexOf(Class<?> cls) {
int index = mActivities.indexOf(cls);
if (-1 == index) {
Log.e(TAG, "No such activity: " + cls.getName());
}
return index;
}
@SuppressWarnings("unused")
private Class<?> getActivityAt(int index) {
if (index > 0 && index < mActivities.size()) {
return mActivities.get(index);
}
return null;
}
/**
* Show next activity(already setCurrentActivity)
*/
@Override
public void showNext() {
mDirection = SHOW_NEXT;
setDisplayedActivity(mWhichActivity + 1, true);
}
/**
* Show next activity of
*
* @param cls
* class of activity
*/
public void showNextOf(Class<?> cls) {
setCurrentActivity(cls);
showNext();
}
/**
* Show next activity(use current context as a activity)
*/
public void autoShowNext() {
showNextOf(mActivity.getClass());
}
/**
* Show previous activity(already setCurrentActivity)
*/
@Override
public void showPrevious() {
mDirection = SHOW_PROVIOUS;
setDisplayedActivity(mWhichActivity - 1, true);
}
/**
* Show previous activity of
*
* @param cls
* class of activity
*/
public void showPreviousOf(Class<?> cls) {
setCurrentActivity(cls);
showPrevious();
}
/**
* Show previous activity(use current context as a activity)
*/
public void autoShowPrevious() {
showPreviousOf(mActivity.getClass());
}
/**
* Sets which child view will be displayed
*
* @param whichActivity
* the index of the child view to display
* @param display
* display immediately
*/
public void setDisplayedActivity(int whichActivity, boolean display) {
mWhichActivity = whichActivity;
if (whichActivity >= getCount()) {
mWhichActivity = 0;
} else if (whichActivity < 0) {
mWhichActivity = getCount() - 1;
}
if (display) {
launchActivity(mWhichActivity);
}
}
/**
* Set current Activity
*
* @param cls
* class of activity
*/
public void setCurrentActivity(Class<?> cls) {
setDisplayedActivity(getIndexOf(cls), false);
}
public void setInAnimation(int resourceId) {
setEnableAnimation(true);
mNextInAnimation = resourceId;
}
public void setOutAnimation(int resourceId) {
setEnableAnimation(true);
mNextOutAnimation = resourceId;
}
public void setPreviousInAnimation(int resourceId) {
mPreviousInAnimation = resourceId;
}
public void setPreviousOutAnimation(int resourceId) {
mPreviousOutAnimation = resourceId;
}
public void setEnableAnimation(boolean enable) {
mAnimationEnabled = enable;
}
/**
* Count activities
*
* @return the number of activities
*/
public int getCount() {
return mActivities.size();
}
}
| Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid.ui.module;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.BrowseActivity;
import com.ch_linghu.fanfoudroid.DmActivity;
import com.ch_linghu.fanfoudroid.FavoritesActivity;
import com.ch_linghu.fanfoudroid.FollowersActivity;
import com.ch_linghu.fanfoudroid.FollowingActivity;
import com.ch_linghu.fanfoudroid.MentionActivity;
import com.ch_linghu.fanfoudroid.ProfileActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.UserTimelineActivity;
/**
* 顶部主菜单切换浮动层
*
* @author lds
*
*/
public class MenuDialog extends Dialog {
private static final int PAGE_MINE = 0;
private static final int PAGE_PROFILE = 1;
private static final int PAGE_FOLLOWERS = 2;
private static final int PAGE_FOLLOWING = 3;
private static final int PAGE_HOME = 4;
private static final int PAGE_MENTIONS = 5;
private static final int PAGE_BROWSE = 6;
private static final int PAGE_FAVORITES = 7;
private static final int PAGE_MESSAGE = 8;
private List<int[]> pages = new ArrayList<int[]>();
{
pages.add(new int[] { R.drawable.menu_tweets,
R.string.pages_mine });
pages.add(new int[] { R.drawable.menu_profile,
R.string.pages_profile });
pages.add(new int[] { R.drawable.menu_followers,
R.string.pages_followers });
pages.add(new int[] { R.drawable.menu_following,
R.string.pages_following });
pages.add(new int[] { R.drawable.menu_list,
R.string.pages_home });
pages.add(new int[] { R.drawable.menu_mentions,
R.string.pages_mentions });
pages.add(new int[] { R.drawable.menu_listed,
R.string.pages_browse });
pages.add(new int[] { R.drawable.menu_favorites,
R.string.pages_search });
pages.add(new int[] { R.drawable.menu_create_list,
R.string.pages_message });
};
private GridView gridview;
public MenuDialog(Context context, boolean cancelable,
OnCancelListener cancelListener) {
super(context, cancelable, cancelListener);
// TODO Auto-generated constructor stub
}
public MenuDialog(Context context, int theme) {
super(context, theme);
// TODO Auto-generated constructor stub
}
public MenuDialog(Context context) {
super(context, R.style.Theme_Transparent);
setContentView(R.layout.menu_dialog);
// setTitle("Custom Dialog");
setCanceledOnTouchOutside(true);
// 设置window属性
LayoutParams a = getWindow().getAttributes();
a.gravity = Gravity.TOP;
a.dimAmount = 0; // 去背景遮盖
getWindow().setAttributes(a);
initMenu();
}
public void setPosition(int x, int y) {
LayoutParams a = getWindow().getAttributes();
if (-1 != x)
a.x = x;
if (-1 != y)
a.y = y;
getWindow().setAttributes(a);
}
private void goTo(Class<?> cls, Intent intent) {
if (getOwnerActivity().getClass() != cls) {
dismiss();
intent.setClass(getContext(), cls);
getContext().startActivity(intent);
} else {
String msg = getContext().getString(R.string.page_status_same_page);
Toast.makeText(getContext(), msg,
Toast.LENGTH_SHORT).show();
}
}
private void goTo(Class<?> cls){
Intent intent = new Intent();
goTo(cls, intent);
}
private void initMenu() {
// 准备要添加的数据条目
List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
for (int[] item : pages) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("image", item[0]);
map.put("title", getContext().getString(item[1]) );
items.add(map);
}
// 实例化一个适配器
SimpleAdapter adapter = new SimpleAdapter(getContext(),
items, // data
R.layout.menu_item, // grid item layout
new String[] { "title", "image" }, // data's key
new int[] { R.id.item_text, R.id.item_image }); // item view id
// 获得GridView实例
gridview = (GridView) findViewById(R.id.mygridview);
// 将GridView和数据适配器关联
gridview.setAdapter(adapter);
}
public void bindEvent(Activity activity) {
setOwnerActivity(activity);
// 绑定监听器
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
switch (position) {
case PAGE_MINE:
String user = TwitterApplication.getMyselfId();
String name = TwitterApplication.getMyselfName();
Intent intent = UserTimelineActivity.createIntent(user, name);
goTo(UserTimelineActivity.class, intent);
break;
case PAGE_PROFILE:
goTo(ProfileActivity.class);
break;
case PAGE_FOLLOWERS:
goTo(FollowersActivity.class);
break;
case PAGE_FOLLOWING:
goTo(FollowingActivity.class);
break;
case PAGE_HOME:
goTo(TwitterActivity.class);
break;
case PAGE_MENTIONS:
goTo(MentionActivity.class);
break;
case PAGE_BROWSE:
goTo(BrowseActivity.class);
break;
case PAGE_FAVORITES:
goTo(FavoritesActivity.class);
break;
case PAGE_MESSAGE:
goTo(DmActivity.class);
break;
}
}
});
Button close_button = (Button) findViewById(R.id.close_menu);
close_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.TextView;
public class TweetEdit {
private EditText mEditText;
private TextView mCharsRemainText;
private int originTextColor;
public TweetEdit(EditText editText, TextView charsRemainText) {
mEditText = editText;
mCharsRemainText = charsRemainText;
originTextColor = mCharsRemainText.getTextColors().getDefaultColor();
mEditText.addTextChangedListener(mTextWatcher);
mEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
MAX_TWEET_INPUT_LENGTH) });
}
private static final int MAX_TWEET_LENGTH = 140;
private static final int MAX_TWEET_INPUT_LENGTH = 400;
public void setTextAndFocus(String text, boolean start) {
setText(text);
Editable editable = mEditText.getText();
if (!start){
Selection.setSelection(editable, editable.length());
}else{
Selection.setSelection(editable, 0);
}
mEditText.requestFocus();
}
public void setText(String text) {
mEditText.setText(text);
updateCharsRemain();
}
private TextWatcher mTextWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable e) {
updateCharsRemain();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
};
public void updateCharsRemain() {
int remaining = MAX_TWEET_LENGTH - mEditText.length();
if (remaining < 0 ) {
mCharsRemainText.setTextColor(Color.RED);
} else {
mCharsRemainText.setTextColor(originTextColor);
}
mCharsRemainText.setText(remaining + "");
}
public String getText() {
return mEditText.getText().toString();
}
public void setEnabled(boolean b) {
mEditText.setEnabled(b);
}
public void setOnKeyListener(OnKeyListener listener) {
mEditText.setOnKeyListener(listener);
}
public void addTextChangedListener(TextWatcher watcher){
mEditText.addTextChangedListener(watcher);
}
public void requestFocus() {
mEditText.requestFocus();
}
public EditText getEditText() {
return mEditText;
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
public interface Feedback {
public boolean isAvailable();
public void start(CharSequence text);
public void cancel(CharSequence text);
public void success(CharSequence text);
public void failed(CharSequence text);
public void update(Object arg0);
public void setIndeterminate (boolean indeterminate);
}
| Java |
/**
*
*/
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.db.UserInfoTable;
public class UserCursorAdapter extends CursorAdapter implements TweetAdapter {
private static final String TAG = "TweetCursorAdapter";
private Context mContext;
public UserCursorAdapter(Context context, Cursor cursor) {
super(context, cursor);
mContext = context;
if (context != null) {
mInflater = LayoutInflater.from(context);
}
if (cursor != null) {
mScreenNametColumn=cursor.getColumnIndexOrThrow(UserInfoTable.FIELD_USER_SCREEN_NAME);
mUserIdColumn=cursor.getColumnIndexOrThrow(UserInfoTable._ID);
mProfileImageUrlColumn=cursor.getColumnIndexOrThrow(UserInfoTable.FIELD_PROFILE_IMAGE_URL);
// mLastStatusColumn=cursor.getColumnIndexOrThrow(UserInfoTable.FIELD_LAST_STATUS);
}
mMetaBuilder = new StringBuilder();
}
private LayoutInflater mInflater;
private int mScreenNametColumn;
private int mUserIdColumn;
private int mProfileImageUrlColumn;
//private int mLastStatusColumn;
private StringBuilder mMetaBuilder;
private ImageLoaderCallback callback = new ImageLoaderCallback(){
@Override
public void refresh(String url, Bitmap bitmap) {
UserCursorAdapter.this.refresh();
}
};
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater.inflate(R.layout.follower_item, parent, false);
Log.d(TAG,"load newView");
UserCursorAdapter.ViewHolder holder = new ViewHolder();
holder.screenName=(TextView) view.findViewById(R.id.screen_name);
holder.profileImage=(ImageView)view.findViewById(R.id.profile_image);
//holder.lastStatus=(TextView) view.findViewById(R.id.last_status);
holder.userId=(TextView) view.findViewById(R.id.user_id);
view.setTag(holder);
return view;
}
private static class ViewHolder {
public TextView screenName;
public TextView userId;
public TextView lastStatus;
public ImageView profileImage;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
UserCursorAdapter.ViewHolder holder = (UserCursorAdapter.ViewHolder) view
.getTag();
Log.d(TAG, "cursor count="+cursor.getCount());
Log.d(TAG,"holder is null?"+(holder==null?"yes":"no"));
SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext);;
boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true);
String profileImageUrl = cursor.getString(mProfileImageUrlColumn);
if (useProfileImage){
if (!TextUtils.isEmpty(profileImageUrl)) {
holder.profileImage.setImageBitmap(TwitterApplication.mImageLoader
.get(profileImageUrl, callback));
}
}else{
holder.profileImage.setVisibility(View.GONE);
}
holder.screenName.setText(cursor.getString(mScreenNametColumn));
holder.userId.setText(cursor.getString(mUserIdColumn));
}
@Override
public void refresh() {
getCursor().requery();
}
} | Java |
package com.ch_linghu.fanfoudroid.ui.module;
import com.ch_linghu.fanfoudroid.R;
import android.app.Activity;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
/**
* FlingGestureLIstener, 封装 {@link SimpleOnGestureListener} .
* 主要用于识别类似向上下或向左右滑动等基本手势.
*
* 该类主要解决了与ListView自带的上下滑动冲突问题.
* 解决方法为将listView的onTouchListener进行覆盖:<code>
* FlingGestureListener gListener = new FlingGestureListener(this,
* MyActivityFlipper.create(this));
* myListView.setOnTouchListener(gListener);
* </code>
*
* 该类一般和实现了 {@link Widget.OnGestureListener} 接口的类共同协作.
* 在识别到手势后会自动调用其相关的回调方法, 以实现手势触发事件效果.
*
* @see Widget.OnGestureListener
*
*/
public class FlingGestureListener extends SimpleOnGestureListener implements
OnTouchListener {
private static final String TAG = "FlipperGestureListener";
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_DISTANCE = 400;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private Widget.OnGestureListener mListener;
private GestureDetector gDetector;
private Activity activity;
public FlingGestureListener(Activity activity,
Widget.OnGestureListener listener) {
this(activity, listener, null);
}
public FlingGestureListener(Activity activity,
Widget.OnGestureListener listener, GestureDetector gDetector) {
if (gDetector == null) {
gDetector = new GestureDetector(activity, this);
}
this.gDetector = gDetector;
mListener = listener;
this.activity = activity;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
Log.d(TAG, "On fling");
boolean result = super.onFling(e1, e2, velocityX, velocityY);
float xDistance = Math.abs(e1.getX() - e2.getX());
float yDistance = Math.abs(e1.getY() - e2.getY());
velocityX = Math.abs(velocityX);
velocityY = Math.abs(velocityY);
try {
if (xDistance > SWIPE_MAX_DISTANCE
|| yDistance > SWIPE_MAX_DISTANCE) {
Log.d(TAG, "OFF_PATH");
return result;
}
if (velocityX > SWIPE_THRESHOLD_VELOCITY
&& xDistance > SWIPE_MIN_DISTANCE) {
if (e1.getX() > e2.getX()) {
Log.d(TAG, "<------");
result = mListener.onFlingLeft(e1, e1, velocityX, velocityY);
activity.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
} else {
Log.d(TAG, "------>");
result = mListener.onFlingRight(e1, e1, velocityX, velocityY);
activity.overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
}
} else if (velocityY > SWIPE_THRESHOLD_VELOCITY
&& yDistance > SWIPE_MIN_DISTANCE) {
if (e1.getY() > e2.getY()) {
Log.d(TAG, "up");
result = mListener.onFlingUp(e1, e1, velocityX, velocityY);
} else {
Log.d(TAG, "down");
result = mListener.onFlingDown(e1, e1, velocityX, velocityY);
}
} else {
Log.d(TAG, "not hint");
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "onFling error " + e.getMessage());
}
return result;
}
@Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
super.onLongPress(e);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d(TAG, "On Touch");
// Within the MyGestureListener class you can now manage the
// event.getAction() codes.
// Note that we are now calling the gesture Detectors onTouchEvent.
// And given we've set this class as the GestureDetectors listener
// the onFling, onSingleTap etc methods will be executed.
return gDetector.onTouchEvent(event);
}
public GestureDetector getDetector() {
return gDetector;
}
} | Java |
/**
*
*/
package com.ch_linghu.fanfoudroid.ui.module;
import java.text.ParseException;
import java.util.Date;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.app.SimpleImageLoader;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class TweetCursorAdapter extends CursorAdapter implements TweetAdapter {
private static final String TAG = "TweetCursorAdapter";
private Context mContext;
public TweetCursorAdapter(Context context, Cursor cursor) {
super(context, cursor);
mContext = context;
if (context != null) {
mInflater = LayoutInflater.from(context);
}
if (cursor != null) {
//TODO: 可使用:
//Tweet tweet = StatusTable.parseCursor(cursor);
mUserTextColumn = cursor
.getColumnIndexOrThrow(StatusTable.USER_SCREEN_NAME);
mTextColumn = cursor.getColumnIndexOrThrow(StatusTable.TEXT);
mProfileImageUrlColumn = cursor
.getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL);
mCreatedAtColumn = cursor
.getColumnIndexOrThrow(StatusTable.CREATED_AT);
mSourceColumn = cursor.getColumnIndexOrThrow(StatusTable.SOURCE);
mInReplyToScreenName = cursor
.getColumnIndexOrThrow(StatusTable.IN_REPLY_TO_SCREEN_NAME);
mFavorited = cursor.getColumnIndexOrThrow(StatusTable.FAVORITED);
mThumbnailPic = cursor.getColumnIndexOrThrow(StatusTable.PIC_THUMB);
mMiddlePic = cursor.getColumnIndexOrThrow(StatusTable.PIC_MID);
mOriginalPic = cursor.getColumnIndexOrThrow(StatusTable.PIC_ORIG);
}
mMetaBuilder = new StringBuilder();
}
private LayoutInflater mInflater;
private int mUserTextColumn;
private int mTextColumn;
private int mProfileImageUrlColumn;
private int mCreatedAtColumn;
private int mSourceColumn;
private int mInReplyToScreenName;
private int mFavorited;
private int mThumbnailPic;
private int mMiddlePic;
private int mOriginalPic;
private StringBuilder mMetaBuilder;
/*
private ProfileImageCacheCallback callback = new ProfileImageCacheCallback(){
@Override
public void refresh(String url, Bitmap bitmap) {
TweetCursorAdapter.this.refresh();
}
};
*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater.inflate(R.layout.tweet, parent, false);
TweetCursorAdapter.ViewHolder holder = new ViewHolder();
holder.tweetUserText = (TextView) view
.findViewById(R.id.tweet_user_text);
holder.tweetText = (TextView) view.findViewById(R.id.tweet_text);
holder.profileImage = (ImageView) view.findViewById(R.id.profile_image);
holder.metaText = (TextView) view.findViewById(R.id.tweet_meta_text);
holder.fav = (ImageView) view.findViewById(R.id.tweet_fav);
holder.has_image = (ImageView) view.findViewById(R.id.tweet_has_image);
view.setTag(holder);
return view;
}
private static class ViewHolder {
public TextView tweetUserText;
public TextView tweetText;
public ImageView profileImage;
public TextView metaText;
public ImageView fav;
public ImageView has_image;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TweetCursorAdapter.ViewHolder holder = (TweetCursorAdapter.ViewHolder) view
.getTag();
SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext);;
boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true);
holder.tweetUserText.setText(cursor.getString(mUserTextColumn));
TextHelper.setSimpleTweetText(holder.tweetText, cursor.getString(mTextColumn));
String profileImageUrl = cursor.getString(mProfileImageUrlColumn);
if (useProfileImage && !TextUtils.isEmpty(profileImageUrl)) {
SimpleImageLoader.display(holder.profileImage, profileImageUrl);
} else {
holder.profileImage.setVisibility(View.GONE);
}
if (cursor.getString(mFavorited).equals("true")) {
holder.fav.setVisibility(View.VISIBLE);
} else {
holder.fav.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(cursor.getString(mThumbnailPic))) {
holder.has_image.setVisibility(View.VISIBLE);
} else {
holder.has_image.setVisibility(View.GONE);
}
try {
Date createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(cursor
.getString(mCreatedAtColumn));
holder.metaText.setText(Tweet.buildMetaText(mMetaBuilder,
createdAt, cursor.getString(mSourceColumn), cursor
.getString(mInReplyToScreenName)));
} catch (ParseException e) {
Log.w(TAG, "Invalid created at data.");
}
}
@Override
public void refresh() {
getCursor().requery();
}
} | Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* This broadcast receiver is awoken after boot and registers the service that
* checks for new tweets.
*/
public class BootReceiver extends BroadcastReceiver {
private static final String TAG = "BootReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Twitta BootReceiver is receiving.");
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
TwitterService.schedule(context);
}
}
}
| Java |
package com.ch_linghu.fanfoudroid.service;
import java.util.List;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
/**
* Location Service
*
* AndroidManifest.xml <code>
* <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
* </code>
*
* TODO: 使用DDMS对模拟器GPS位置进行更新时, 会造成死机现象
*
*/
public class LocationService implements IService {
private static final String TAG = "LocationService";
private LocationManager mLocationManager;
private LocationListener mLocationListener = new MyLocationListener();
private String mLocationProvider;
private boolean running = false;
public LocationService(Context context) {
initLocationManager(context);
}
private void initLocationManager(Context context) {
// Acquire a reference to the system Location Manager
mLocationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
mLocationProvider = mLocationManager.getBestProvider(new Criteria(),
false);
}
public void startService() {
if (!running) {
Log.v(TAG, "START LOCATION SERVICE, PROVIDER:" + mLocationProvider);
running = true;
mLocationManager.requestLocationUpdates(mLocationProvider, 0, 0,
mLocationListener);
}
}
public void stopService() {
if (running) {
Log.v(TAG, "STOP LOCATION SERVICE");
running = false;
mLocationManager.removeUpdates(mLocationListener);
}
}
/**
* @return the last known location for the provider, or null
*/
public Location getLastKnownLocation() {
return mLocationManager.getLastKnownLocation(mLocationProvider);
}
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.v(TAG, "LOCATION CHANGED TO: " + location.toString());
}
@Override
public void onProviderDisabled(String provider) {
Log.v(TAG, "PROVIDER DISABLED " + provider);
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
Log.v(TAG, "PROVIDER ENABLED " + provider);
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
Log.v(TAG, "STATUS CHANGED: " + provider + " " + status);
}
}
// Only for debug
public void logAllProviders() {
// List all providers:
List<String> providers = mLocationManager.getAllProviders();
Log.v(TAG, "LIST ALL PROVIDERS:");
for (String provider : providers) {
boolean isEnabled = mLocationManager.isProviderEnabled(provider);
Log.v(TAG, "Provider " + provider + ": " + isEnabled);
}
}
// only for debug
public static LocationService test(Context context) {
LocationService ls = new LocationService(context);
ls.startService();
ls.logAllProviders();
Location local = ls.getLastKnownLocation();
if (local != null) {
Log.v("LDS", ls.getLastKnownLocation().toString());
}
return ls;
}
}
| Java |
package com.ch_linghu.fanfoudroid.service;
public interface IService {
void startService();
void stopService();
}
| Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid.service;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import com.ch_linghu.fanfoudroid.DmActivity;
import com.ch_linghu.fanfoudroid.FanfouWidget;
import com.ch_linghu.fanfoudroid.MentionActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Dm;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.Weibo;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class TwitterService extends Service {
private static final String TAG = "TwitterService";
private NotificationManager mNotificationManager;
private ArrayList<Tweet> mNewTweets;
private ArrayList<Tweet> mNewMentions;
private ArrayList<Dm> mNewDms;
private GenericTask mRetrieveTask;
public String getUserId() {
return TwitterApplication.getMyselfId();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// fetchMessages();
// handler.postDelayed(mTask, 10000);
Log.d(TAG, "Start Once");
return super.onStartCommand(intent, flags, startId);
}
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
SharedPreferences preferences = TwitterApplication.mPref;
boolean needCheck = preferences.getBoolean(
Preferences.CHECK_UPDATES_KEY, false);
boolean timeline_only = preferences.getBoolean(
Preferences.TIMELINE_ONLY_KEY, false);
boolean replies_only = preferences.getBoolean(
Preferences.REPLIES_ONLY_KEY, true);
boolean dm_only = preferences.getBoolean(
Preferences.DM_ONLY_KEY, true);
if (needCheck) {
if (timeline_only) {
processNewTweets();
}
if (replies_only) {
processNewMentions();
}
if (dm_only) {
processNewDms();
}
}
}
try {
Intent intent = new Intent(TwitterService.this,
FanfouWidget.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
PendingIntent pi = PendingIntent.getBroadcast(
TwitterService.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
pi.send();
} catch (CanceledException e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
stopSelf();
}
@Override
public String getName() {
return "ServiceRetrieveTask";
}
};
private WakeLock mWakeLock;
@Override
public IBinder onBind(Intent intent) {
return null;
}
private TwitterDatabase getDb() {
return TwitterApplication.mDb;
}
private Weibo getApi() {
return TwitterApplication.mApi;
}
@Override
public void onCreate() {
Log.v(TAG, "Server Created");
super.onCreate();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
mWakeLock.acquire();
boolean needCheck = TwitterApplication.mPref.getBoolean(
Preferences.CHECK_UPDATES_KEY, false);
boolean widgetIsEnabled = TwitterService.widgetIsEnabled;
Log.v(TAG, "Check Updates is " + needCheck + "/wg:" + widgetIsEnabled);
if (!needCheck && !widgetIsEnabled) {
Log.d(TAG, "Check update preference is false.");
stopSelf();
return;
}
if (!getApi().isLoggedIn()) {
Log.d(TAG, "Not logged in.");
stopSelf();
return;
}
schedule(TwitterService.this);
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNewTweets = new ArrayList<Tweet>();
mNewMentions = new ArrayList<Tweet>();
mNewDms = new ArrayList<Dm>();
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new RetrieveTask();
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute((TaskParams[]) null);
}
}
private void processNewTweets() {
int count = mNewTweets.size();
if (count <= 0) {
return;
}
Tweet latestTweet = mNewTweets.get(0);
String title;
String text;
if (count == 1) {
title = latestTweet.screenName;
text = TextHelper.getSimpleTweetText(latestTweet.text);
} else {
title = getString(R.string.service_new_twitter_updates);
text = getString(R.string.service_x_new_tweets);
text = MessageFormat.format(text, count);
}
PendingIntent intent = PendingIntent.getActivity(this, 0,
TwitterActivity.createIntent(this), 0);
notify(intent, TWEET_NOTIFICATION_ID, R.drawable.notify_tweet,
TextHelper.getSimpleTweetText(latestTweet.text), title, text);
}
private void processNewMentions() {
int count = mNewMentions.size();
if (count <= 0) {
return;
}
Tweet latestTweet = mNewMentions.get(0);
String title;
String text;
if (count == 1) {
title = latestTweet.screenName;
text = TextHelper.getSimpleTweetText(latestTweet.text);
} else {
title = getString(R.string.service_new_mention_updates);
text = getString(R.string.service_x_new_mentions);
text = MessageFormat.format(text, count);
}
PendingIntent intent = PendingIntent.getActivity(this, 0,
MentionActivity.createIntent(this), 0);
notify(intent, MENTION_NOTIFICATION_ID, R.drawable.notify_mention,
TextHelper.getSimpleTweetText(latestTweet.text), title, text);
}
private static int TWEET_NOTIFICATION_ID = 0;
private static int DM_NOTIFICATION_ID = 1;
private static int MENTION_NOTIFICATION_ID = 2;
private void notify(PendingIntent intent, int notificationId,
int notifyIconId, String tickerText, String title, String text) {
Notification notification = new Notification(notifyIconId, tickerText,
System.currentTimeMillis());
notification.setLatestEventInfo(this, title, text, intent);
notification.flags = Notification.FLAG_AUTO_CANCEL
| Notification.FLAG_ONLY_ALERT_ONCE
| Notification.FLAG_SHOW_LIGHTS;
notification.ledARGB = 0xFF84E4FA;
notification.ledOnMS = 5000;
notification.ledOffMS = 5000;
String ringtoneUri = TwitterApplication.mPref.getString(
Preferences.RINGTONE_KEY, null);
if (ringtoneUri == null) {
notification.defaults |= Notification.DEFAULT_SOUND;
} else {
notification.sound = Uri.parse(ringtoneUri);
}
if (TwitterApplication.mPref.getBoolean(Preferences.VIBRATE_KEY, false)) {
notification.defaults |= Notification.DEFAULT_VIBRATE;
}
mNotificationManager.notify(notificationId, notification);
}
private void processNewDms() {
int count = mNewDms.size();
if (count <= 0) {
return;
}
Dm latest = mNewDms.get(0);
String title;
String text;
if (count == 1) {
title = latest.screenName;
text = TextHelper.getSimpleTweetText(latest.text);
} else {
title = getString(R.string.service_new_direct_message_updates);
text = getString(R.string.service_x_new_direct_messages);
text = MessageFormat.format(text, count);
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
DmActivity.createIntent(), 0);
notify(pendingIntent, DM_NOTIFICATION_ID, R.drawable.notify_dm,
TextHelper.getSimpleTweetText(latest.text), title, text);
}
@Override
public void onDestroy() {
Log.d(TAG, "Service Destroy.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
mRetrieveTask.cancel(true);
}
mWakeLock.release();
super.onDestroy();
}
public static void schedule(Context context) {
SharedPreferences preferences = TwitterApplication.mPref;
boolean needCheck = preferences.getBoolean(
Preferences.CHECK_UPDATES_KEY, false);
boolean widgetIsEnabled = TwitterService.widgetIsEnabled;
if (!needCheck && !widgetIsEnabled) {
Log.d(TAG, "Check update preference is false.");
return;
}
String intervalPref = preferences
.getString(
Preferences.CHECK_UPDATE_INTERVAL_KEY,
context.getString(R.string.pref_check_updates_interval_default));
int interval = Integer.parseInt(intervalPref);
// interval = 1; //for debug
Intent intent = new Intent(context, TwitterService.class);
PendingIntent pending = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar c = new GregorianCalendar();
c.add(Calendar.MINUTE, interval);
DateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
Log.d(TAG, "Schedule, next run at " + df.format(c.getTime()));
AlarmManager alarm = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pending);
if (needCheck) {
alarm.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pending);
} else {
// only for widget
alarm.set(AlarmManager.RTC, c.getTimeInMillis(), pending);
}
}
public static void unschedule(Context context) {
Intent intent = new Intent(context, TwitterService.class);
PendingIntent pending = PendingIntent.getService(context, 0, intent, 0);
AlarmManager alarm = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Log.d(TAG, "Cancelling alarms.");
alarm.cancel(pending);
}
private static boolean widgetIsEnabled = false;
public static void setWidgetStatus(boolean isEnabled) {
widgetIsEnabled = isEnabled;
}
public static boolean isWidgetEnabled() {
return widgetIsEnabled;
}
private class RetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
SharedPreferences preferences = TwitterApplication.mPref;
boolean timeline_only = preferences.getBoolean(
Preferences.TIMELINE_ONLY_KEY, false);
boolean replies_only = preferences.getBoolean(
Preferences.REPLIES_ONLY_KEY, true);
boolean dm_only = preferences.getBoolean(Preferences.DM_ONLY_KEY,
true);
Log.d(TAG, "Widget Is Enabled? " + TwitterService.widgetIsEnabled);
if (timeline_only || TwitterService.widgetIsEnabled) {
String maxId = getDb()
.fetchMaxTweetId(TwitterApplication.getMyselfId(),
StatusTable.TYPE_HOME);
Log.d(TAG, "Max id is:" + maxId);
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
try {
if (maxId != null) {
statusList = getApi().getFriendsTimeline(
new Paging(maxId));
} else {
statusList = getApi().getFriendsTimeline();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Tweet tweet;
tweet = Tweet.create(status);
mNewTweets.add(tweet);
Log.d(TAG, mNewTweets.size() + " new tweets.");
int count = getDb().addNewTweetsAndCountUnread(mNewTweets,
TwitterApplication.getMyselfId(),
StatusTable.TYPE_HOME);
if (count <= 0) {
return TaskResult.FAILED;
}
}
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
if (replies_only) {
String maxMentionId = getDb().fetchMaxTweetId(
TwitterApplication.getMyselfId(),
StatusTable.TYPE_MENTION);
Log.d(TAG, "Max mention id is:" + maxMentionId);
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
try {
if (maxMentionId != null) {
statusList = getApi().getMentions(
new Paging(maxMentionId));
} else {
statusList = getApi().getMentions();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
int unReadMentionsCount = 0;
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Tweet tweet = Tweet.create(status);
mNewMentions.add(tweet);
unReadMentionsCount = getDb().addNewTweetsAndCountUnread(
mNewMentions, TwitterApplication.getMyselfId(),
StatusTable.TYPE_MENTION);
if (unReadMentionsCount <= 0) {
return TaskResult.FAILED;
}
}
Log.v(TAG, "Got mentions " + unReadMentionsCount + "/"
+ mNewMentions.size());
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
if (dm_only) {
String maxId = getDb().fetchMaxDmId(false);
Log.d(TAG, "Max DM id is:" + maxId);
List<com.ch_linghu.fanfoudroid.fanfou.DirectMessage> dmList;
try {
if (maxId != null) {
dmList = getApi().getDirectMessages(new Paging(maxId));
} else {
dmList = getApi().getDirectMessages();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
for (com.ch_linghu.fanfoudroid.fanfou.DirectMessage directMessage : dmList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Dm dm;
dm = Dm.create(directMessage, false);
mNewDms.add(dm);
Log.d(TAG, mNewDms.size() + " new DMs.");
int count = 0;
TwitterDatabase db = getDb();
if (db.fetchDmCount() > 0) {
count = db.addNewDmsAndCountUnread(mNewDms);
} else {
Log.d(TAG, "No existing DMs. Don't notify.");
db.addDms(mNewDms, false);
}
if (count <= 0) {
return TaskResult.FAILED;
}
}
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
return TaskResult.OK;
}
}
}
| Java |
package com.ch_linghu.fanfoudroid.service;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;
import com.ch_linghu.fanfoudroid.FanfouWidget;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
public class WidgetService extends Service {
protected static final String TAG = "WidgetService";
private int position = 0;
private List<Tweet> tweets;
private TwitterDatabase getDb() {
return TwitterApplication.mDb;
}
public String getUserId() {
return TwitterApplication.getMyselfId();
}
private void fetchMessages() {
if (tweets == null) {
tweets = new ArrayList<Tweet>();
}else{
tweets.clear();
}
Cursor cursor = getDb().fetchAllTweets(getUserId(),
StatusTable.TYPE_HOME);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Tweet tweet = StatusTable.parseCursor(cursor);
tweets.add(tweet);
} while (cursor.moveToNext());
}
}
}
public RemoteViews buildUpdate(Context context) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_initial_layout);
updateViews
.setTextViewText(R.id.status_text, tweets.get(position).text);
//updateViews.setOnClickPendingIntent(viewId, pendingIntent)
position++;
return updateViews;
}
private Handler handler = new Handler();
private Runnable mTask = new Runnable() {
@Override
public void run() {
Log.d(TAG, "tweets size="+tweets.size()+" position=" + position);
if (position >= tweets.size()) {
position = 0;
}
ComponentName fanfouWidget = new ComponentName(WidgetService.this,
FanfouWidget.class);
AppWidgetManager manager = AppWidgetManager
.getInstance(getBaseContext());
manager.updateAppWidget(fanfouWidget,
buildUpdate(WidgetService.this));
handler.postDelayed(mTask, 10000);
}
};
public static void schedule(Context context) {
SharedPreferences preferences = TwitterApplication.mPref;
if (!preferences.getBoolean(Preferences.CHECK_UPDATES_KEY, false)) {
Log.d(TAG, "Check update preference is false.");
return;
}
String intervalPref = preferences
.getString(
Preferences.CHECK_UPDATE_INTERVAL_KEY,
context.getString(R.string.pref_check_updates_interval_default));
int interval = Integer.parseInt(intervalPref);
Intent intent = new Intent(context, WidgetService.class);
PendingIntent pending = PendingIntent.getService(context, 0, intent, 0);
Calendar c = new GregorianCalendar();
c.add(Calendar.MINUTE, interval);
DateFormat df = new SimpleDateFormat("h:mm a");
Log.d(TAG, "Scheduling alarm at " + df.format(c.getTime()));
AlarmManager alarm = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pending);
alarm.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pending);
}
/**
* @see android.app.Service#onBind(Intent)
*/
@Override
public IBinder onBind(Intent intent) {
// TODO Put your code here
return null;
}
/**
* @see android.app.Service#onCreate()
*/
@Override
public void onCreate() {
Log.d(TAG, "WidgetService onCreate");
schedule(WidgetService.this);
}
/**
* @see android.app.Service#onStart(Intent,int)
*/
@Override
public void onStart(Intent intent, int startId) {
Log.d(TAG, "WidgetService onStart");
fetchMessages();
handler.removeCallbacks(mTask);
handler.postDelayed(mTask, 10000);
}
@Override
public void onDestroy() {
Log.d(TAG, "WidgetService Stop ");
handler.removeCallbacks(mTask);//当服务结束时,删除线程
super.onDestroy();
}
}
| Java |
package com.ch_linghu.fanfoudroid;
import java.text.MessageFormat;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.UserArrayBaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter;
public class FollowersActivity extends UserArrayBaseActivity {
private ListView mUserList;
private UserArrayAdapter mAdapter;
private static final String TAG = "FollowersActivity";
private String userId;
private String userName;
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FOLLOWERS";
private static final String USER_ID = "userId";
private static final String USER_NAME = "userName";
private int currentPage=1;
private int followersCount=0;
private static final double PRE_PAGE_COUNT=100.0;//官方分页为每页100
private int pageCount=0;
private String[] ids;
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
this.userId = extras.getString(USER_ID);
this.userName = extras.getString(USER_NAME);
} else {
// 获取登录用户id
userId=TwitterApplication.getMyselfId();
userName=TwitterApplication.getMyselfName();
}
if (super._onCreate(savedInstanceState)) {
String myself = TwitterApplication.getMyselfId();
if(getUserId()==myself){
mNavbar.setHeaderTitle(MessageFormat.format(
getString(R.string.profile_followers_count_title), "我"));
} else {
mNavbar.setHeaderTitle(MessageFormat.format(
getString(R.string.profile_followers_count_title), userName));
}
return true;
}else{
return false;
}
}
public static Intent createIntent(String userId, String userName) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(USER_ID, userId);
intent.putExtra(USER_NAME, userName);
return intent;
}
@Override
public Paging getNextPage() {
currentPage+=1;
return new Paging(currentPage);
}
@Override
protected String getUserId() {
return this.userId;
}
@Override
public Paging getCurrentPage() {
return new Paging(this.currentPage);
}
@Override
protected List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers(
String userId, Paging page) throws HttpException {
return getApi().getFollowersList(userId, page);
}
}
| Java |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.app.ImageCache;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.http.HttpClient;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.task.TweetCommonTask;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class StatusActivity extends BaseActivity {
private static final String TAG = "StatusActivity";
private static final String SIS_RUNNING_KEY = "running";
private static final String PREFS_NAME = "com.ch_linghu.fanfoudroid";
private static final String EXTRA_TWEET = "tweet";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.STATUS";
static final private int CONTEXT_REFRESH_ID = 0x0001;
static final private int CONTEXT_CLIPBOARD_ID = 0x0002;
static final private int CONTEXT_DELETE_ID = 0x0003;
// Task TODO: tasks
private GenericTask mReplyTask;
private GenericTask mStatusTask;
private GenericTask mPhotoTask; // TODO: 压缩图片,提供获取图片的过程中可取消获取
private GenericTask mFavTask;
private GenericTask mDeleteTask;
private NavBar mNavbar;
private Feedback mFeedback;
private TaskListener mReplyTaskListener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
showReplyStatus(replyTweet);
StatusActivity.this.mFeedback.success("");
}
@Override
public String getName() {
return "GetReply";
}
};
private TaskListener mStatusTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
clean();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
StatusActivity.this.mFeedback.success("");
draw();
}
@Override
public String getName() {
return "GetStatus";
}
};
private TaskListener mPhotoTaskListener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
status_photo.setImageBitmap(mPhotoBitmap);
} else {
status_photo.setVisibility(View.GONE);
}
StatusActivity.this.mFeedback.success("");
}
@Override
public String getName() {
// TODO Auto-generated method stub
return "GetPhoto";
}
};
private TaskListener mFavTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "FavoriteTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onFavSuccess();
} else if (result == TaskResult.IO_ERROR) {
onFavFailure();
}
}
};
private TaskListener mDeleteTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "DeleteTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onDeleteSuccess();
} else if (result == TaskResult.IO_ERROR) {
onDeleteFailure();
}
}
};
// View
private TextView tweet_screen_name;
private TextView tweet_text;
private TextView tweet_user_info;
private ImageView profile_image;
private TextView tweet_source;
private TextView tweet_created_at;
private ImageButton btn_person_more;
private ImageView status_photo = null; // if exists
private ViewGroup reply_wrap;
private TextView reply_status_text = null; // if exists
private TextView reply_status_date = null; // if exists
private ImageButton tweet_fav;
private Tweet tweet = null;
private Tweet replyTweet = null; // if exists
private HttpClient mClient;
private Bitmap mPhotoBitmap = ImageCache.mDefaultBitmap; // if exists
public static Intent createIntent(Tweet tweet) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.putExtra(EXTRA_TWEET, tweet);
return intent;
}
private static Pattern PHOTO_PAGE_LINK = Pattern
.compile("http://fanfou.com(/photo/[-a-zA-Z0-9+&@#%?=~_|!:,.;]*[-a-zA-Z0-9+&@#%=~_|])");
private static Pattern PHOTO_SRC_LINK = Pattern
.compile("src=\"(http:\\/\\/photo\\.fanfou\\.com\\/.*?)\"");
/**
* 获得消息中的照片页面链接
*
* @param text
* 消息文本
* @param size
* 照片尺寸
* @return 照片页面的链接,若不存在,则返回null
*/
public static String getPhotoPageLink(String text, String size) {
Matcher m = PHOTO_PAGE_LINK.matcher(text);
if (m.find()) {
String THUMBNAIL = TwitterApplication.mContext
.getString(R.string.pref_photo_preview_type_thumbnail);
String MIDDLE = TwitterApplication.mContext
.getString(R.string.pref_photo_preview_type_middle);
String ORIGINAL = TwitterApplication.mContext
.getString(R.string.pref_photo_preview_type_original);
if (size.equals(THUMBNAIL) || size.equals(MIDDLE)) {
return "http://m.fanfou.com" + m.group(1);
} else if (size.endsWith(ORIGINAL)) {
return m.group(0);
} else {
return null;
}
} else {
return null;
}
}
/**
* 获得照片页面中的照片链接
*
* @param pageHtml
* 照片页面文本
* @return 照片链接,若不存在,则返回null
*/
public static String getPhotoURL(String pageHtml) {
Matcher m = PHOTO_SRC_LINK.matcher(pageHtml);
if (m.find()) {
return m.group(1);
} else {
return null;
}
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)) {
mClient = getApi().getHttpClient();
// Intent & Action & Extras
Intent intent = getIntent();
String action = intent.getAction();
Bundle extras = intent.getExtras();
// Must has extras
if (null == extras) {
Log.e(TAG, this.getClass().getName() + " must has extras.");
finish();
return false;
}
setContentView(R.layout.status);
mNavbar = new NavBar(NavBar.HEADER_STYLE_BACK, this);
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
findView();
bindNavBarListener();
// Set view with intent data
this.tweet = extras.getParcelable(EXTRA_TWEET);
draw();
bindFooterBarListener();
bindReplyViewListener();
return true;
} else {
return false;
}
}
private void findView() {
tweet_screen_name = (TextView) findViewById(R.id.tweet_screen_name);
tweet_user_info = (TextView) findViewById(R.id.tweet_user_info);
tweet_text = (TextView) findViewById(R.id.tweet_text);
tweet_source = (TextView) findViewById(R.id.tweet_source);
profile_image = (ImageView) findViewById(R.id.profile_image);
tweet_created_at = (TextView) findViewById(R.id.tweet_created_at);
btn_person_more = (ImageButton) findViewById(R.id.person_more);
tweet_fav = (ImageButton) findViewById(R.id.tweet_fav);
reply_wrap = (ViewGroup) findViewById(R.id.reply_wrap);
reply_status_text = (TextView) findViewById(R.id.reply_status_text);
reply_status_date = (TextView) findViewById(R.id.reply_tweet_created_at);
status_photo = (ImageView) findViewById(R.id.status_photo);
}
private void bindNavBarListener() {
mNavbar.getRefreshButton().setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
doGetStatus(tweet.id);
}
});
}
private void bindFooterBarListener() {
// person_more
btn_person_more.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = ProfileActivity.createIntent(tweet.userId);
startActivity(intent);
}
});
// Footer bar
TextView footer_btn_share = (TextView) findViewById(R.id.footer_btn_share);
TextView footer_btn_reply = (TextView) findViewById(R.id.footer_btn_reply);
TextView footer_btn_retweet = (TextView) findViewById(R.id.footer_btn_retweet);
TextView footer_btn_fav = (TextView) findViewById(R.id.footer_btn_fav);
TextView footer_btn_more = (TextView) findViewById(R.id.footer_btn_more);
// 分享
footer_btn_share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(
Intent.EXTRA_TEXT,
String.format("@%s %s", tweet.screenName,
TextHelper.getSimpleTweetText(tweet.text)));
startActivity(Intent.createChooser(intent,
getString(R.string.cmenu_share)));
}
});
// 回复
footer_btn_reply.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = WriteActivity.createNewReplyIntent(
tweet.text, tweet.screenName, tweet.id);
startActivity(intent);
}
});
// 转发
footer_btn_retweet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = WriteActivity.createNewRepostIntent(
StatusActivity.this, tweet.text, tweet.screenName,
tweet.id);
startActivity(intent);
}
});
// 收藏/取消收藏
footer_btn_fav.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (tweet.favorited.equals("true")) {
doFavorite("del", tweet.id);
} else {
doFavorite("add", tweet.id);
}
}
});
// TODO: 更多操作
registerForContextMenu(footer_btn_more);
footer_btn_more.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openContextMenu(v);
}
});
}
private void bindReplyViewListener() {
// 点击回复消息打开新的Status界面
OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!TextUtils.isEmpty(tweet.inReplyToStatusId)) {
if (replyTweet == null) {
Log.w(TAG, "Selected item not available.");
} else {
launchActivity(StatusActivity.createIntent(replyTweet));
}
}
}
};
reply_wrap.setOnClickListener(listener);
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause.");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart.");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume.");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart.");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop.");
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mReplyTask != null
&& mReplyTask.getStatus() == GenericTask.Status.RUNNING) {
mReplyTask.cancel(true);
}
if (mPhotoTask != null
&& mPhotoTask.getStatus() == GenericTask.Status.RUNNING) {
mPhotoTask.cancel(true);
}
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
mFavTask.cancel(true);
}
super.onDestroy();
}
private ImageLoaderCallback callback = new ImageLoaderCallback() {
@Override
public void refresh(String url, Bitmap bitmap) {
profile_image.setImageBitmap(bitmap);
}
};
private void clean() {
tweet_screen_name.setText("");
tweet_text.setText("");
tweet_created_at.setText("");
tweet_source.setText("");
tweet_user_info.setText("");
tweet_fav.setEnabled(false);
profile_image.setImageBitmap(ImageCache.mDefaultBitmap);
status_photo.setVisibility(View.GONE);
ViewGroup reply_wrap = (ViewGroup) findViewById(R.id.reply_wrap);
reply_wrap.setVisibility(View.GONE);
}
private void draw() {
Log.d(TAG, "draw");
String PHOTO_PREVIEW_TYPE_NONE = getString(R.string.pref_photo_preview_type_none);
String PHOTO_PREVIEW_TYPE_THUMBNAIL = getString(R.string.pref_photo_preview_type_thumbnail);
String PHOTO_PREVIEW_TYPE_MIDDLE = getString(R.string.pref_photo_preview_type_middle);
String PHOTO_PREVIEW_TYPE_ORIGINAL = getString(R.string.pref_photo_preview_type_original);
SharedPreferences pref = getPreferences();
String photoPreviewSize = pref.getString(Preferences.PHOTO_PREVIEW,
PHOTO_PREVIEW_TYPE_ORIGINAL);
boolean forceShowAllImage = pref.getBoolean(
Preferences.FORCE_SHOW_ALL_IMAGE, false);
tweet_screen_name.setText(tweet.screenName);
TextHelper.setTweetText(tweet_text, tweet.text);
tweet_created_at.setText(DateTimeHelper.getRelativeDate(tweet.createdAt));
tweet_source.setText(getString(R.string.tweet_source_prefix)
+ tweet.source);
tweet_user_info.setText(tweet.userId);
boolean isFav = (tweet.favorited.equals("true")) ? true : false;
tweet_fav.setEnabled(isFav);
// Bitmap mProfileBitmap =
// TwitterApplication.mImageManager.get(tweet.profileImageUrl);
profile_image
.setImageBitmap(TwitterApplication.mImageLoader
.get(tweet.profileImageUrl, callback));
// has photo
if (!photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_NONE)) {
String photoLink;
boolean isPageLink = false;
if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_THUMBNAIL)) {
photoLink = tweet.thumbnail_pic;
} else if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_MIDDLE)) {
photoLink = tweet.bmiddle_pic;
} else if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_ORIGINAL)) {
photoLink = tweet.original_pic;
} else {
Log.e(TAG, "Invalid Photo Preview Size Type");
photoLink = "";
}
// 如果选用了强制显示则再尝试分析图片链接
if (forceShowAllImage) {
photoLink = getPhotoPageLink(tweet.text, photoPreviewSize);
isPageLink = true;
}
if (!TextUtils.isEmpty(photoLink)) {
status_photo.setVisibility(View.VISIBLE);
status_photo.setImageBitmap(mPhotoBitmap);
doGetPhoto(photoLink, isPageLink);
}
} else {
status_photo.setVisibility(View.GONE);
}
// has reply
if (!TextUtils.isEmpty(tweet.inReplyToStatusId)) {
ViewGroup reply_wrap = (ViewGroup) findViewById(R.id.reply_wrap);
reply_wrap.setVisibility(View.VISIBLE);
reply_status_text = (TextView) findViewById(R.id.reply_status_text);
reply_status_date = (TextView) findViewById(R.id.reply_tweet_created_at);
doGetReply(tweet.inReplyToStatusId);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mReplyTask != null
&& mReplyTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
private String fetchWebPage(String url) throws HttpException {
Log.d(TAG, "Fetching WebPage: " + url);
Response res = mClient.get(url);
return res.asString();
}
private Bitmap fetchPhotoBitmap(String url) throws HttpException,
IOException {
Log.d(TAG, "Fetching Photo: " + url);
Response res = mClient.get(url);
//FIXME:这里使用了一个作废的方法,如何修正?
InputStream is = res.asStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();
return bitmap;
}
private void doGetReply(String status_id) {
Log.d(TAG, "Attempting get status task.");
mFeedback.start("");
if (mReplyTask != null
&& mReplyTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mReplyTask = new GetReplyTask();
mReplyTask.setListener(mReplyTaskListener);
TaskParams params = new TaskParams();
params.put("reply_id", status_id);
mReplyTask.execute(params);
}
}
private class GetReplyTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
com.ch_linghu.fanfoudroid.fanfou.Status status;
try {
String reply_id = param.getString("reply_id");
if (!TextUtils.isEmpty(reply_id)) {
// 首先查看是否在数据库中,如不在再去获取
replyTweet = getDb().queryTweet(reply_id, -1);
if (replyTweet == null) {
status = getApi().showStatus(reply_id);
replyTweet = Tweet.create(status);
}
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
private void doGetStatus(String status_id) {
Log.d(TAG, "Attempting get status task.");
mFeedback.start("");
if (mStatusTask != null
&& mStatusTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mStatusTask = new GetStatusTask();
mStatusTask.setListener(mStatusTaskListener);
TaskParams params = new TaskParams();
params.put("id", status_id);
mStatusTask.execute(params);
}
}
private class GetStatusTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
com.ch_linghu.fanfoudroid.fanfou.Status status;
try {
String id = param.getString("id");
if (!TextUtils.isEmpty(id)) {
status = getApi().showStatus(id);
mFeedback.update(80);
tweet = Tweet.create(status);
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
mFeedback.update(99);
return TaskResult.OK;
}
}
private void doGetPhoto(String photoPageURL, boolean isPageLink) {
mFeedback.start("");
if (mPhotoTask != null
&& mPhotoTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mPhotoTask = new GetPhotoTask();
mPhotoTask.setListener(mPhotoTaskListener);
TaskParams params = new TaskParams();
params.put("photo_url", photoPageURL);
params.put("is_page_link", isPageLink);
mPhotoTask.execute(params);
}
}
private class GetPhotoTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
try {
String photoURL = param.getString("photo_url");
boolean isPageLink = param.getBoolean("is_page_link");
if (!TextUtils.isEmpty(photoURL)) {
if (isPageLink) {
String pageHtml = fetchWebPage(photoURL);
String photoSrcURL = getPhotoURL(pageHtml);
if (photoSrcURL != null) {
mPhotoBitmap = fetchPhotoBitmap(photoSrcURL);
}
} else {
mPhotoBitmap = fetchPhotoBitmap(photoURL);
}
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
private void showReplyStatus(Tweet tweet) {
if (tweet != null) {
String text = tweet.screenName + " : " + tweet.text;
TextHelper.setSimpleTweetText(reply_status_text, text);
reply_status_date.setText(DateTimeHelper.getRelativeDate(tweet.createdAt));
} else {
String msg = MessageFormat.format(
getString(R.string.status_status_reply_cannot_display),
this.tweet.inReplyToScreenName);
reply_status_text.setText(msg);
}
}
public void onDeleteFailure() {
Log.e(TAG, "Delete failed");
}
public void onDeleteSuccess() {
finish();
}
// for HasFavorite interface
public void doFavorite(String action, String id) {
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
if (!TextUtils.isEmpty(id)) {
Log.d(TAG, "doFavorite.");
mFavTask = new TweetCommonTask.FavoriteTask(this);
mFavTask.setListener(mFavTaskListener);
TaskParams param = new TaskParams();
param.put("action", action);
param.put("id", id);
mFavTask.execute(param);
}
}
}
public void onFavSuccess() {
// updateProgress(getString(R.string.refreshing));
if (((TweetCommonTask.FavoriteTask) mFavTask).getType().equals(
TweetCommonTask.FavoriteTask.TYPE_ADD)) {
tweet.favorited = "true";
tweet_fav.setEnabled(true);
} else {
tweet.favorited = "false";
tweet_fav.setEnabled(false);
}
}
public void onFavFailure() {
// updateProgress(getString(R.string.refreshing));
}
private void doDelete(String id) {
if (mDeleteTask != null
&& mDeleteTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mDeleteTask = new TweetCommonTask.DeleteTask(this);
mDeleteTask.setListener(mDeleteTaskListener);
TaskParams params = new TaskParams();
params.put("id", id);
mDeleteTask.execute(params);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case CONTEXT_REFRESH_ID:
doGetStatus(tweet.id);
return true;
case CONTEXT_CLIPBOARD_ID:
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(TextHelper.getSimpleTweetText(tweet.text));
return true;
case CONTEXT_DELETE_ID:
doDelete(tweet.id);
return true;
}
return super.onContextItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
menu.setHeaderIcon(android.R.drawable.ic_menu_more);
menu.setHeaderTitle(getString(R.string.cmenu_more));
menu.add(0, CONTEXT_REFRESH_ID, 0, R.string.omenu_refresh);
menu.add(0, CONTEXT_CLIPBOARD_ID, 0, R.string.cmenu_clipboard);
if (tweet.userId.equals(TwitterApplication.getMyselfId())) {
menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete);
}
}
} | Java |
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.fanfou.SavedSearch;
import com.ch_linghu.fanfoudroid.fanfou.Trend;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.util.TextHelper;
import com.commonsware.cwac.merge.MergeAdapter;
public class SearchActivity extends BaseActivity {
private static final String TAG = SearchActivity.class.getSimpleName();
private static final int LOADING = 1;
private static final int NETWORKERROR = 2;
private static final int SUCCESS = 3;
private EditText mSearchEdit;
private ListView mSearchSectionList;
private TextView trendsTitle;
private TextView savedSearchTitle;
private MergeAdapter mSearchSectionAdapter;
private SearchAdapter trendsAdapter;
private SearchAdapter savedSearchesAdapter;
private ArrayList<SearchItem> trends;
private ArrayList<SearchItem> savedSearch;
private String initialQuery;
private NavBar mNavbar;
private Feedback mFeedback;
private GenericTask trendsAndSavedSearchesTask;
private TaskListener trendsAndSavedSearchesTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "trendsAndSavedSearchesTask";
}
@Override
public void onPreExecute(GenericTask task) {
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
refreshSearchSectionList(SearchActivity.SUCCESS);
} else if (result == TaskResult.IO_ERROR) {
refreshSearchSectionList(SearchActivity.NETWORKERROR);
Toast.makeText(
SearchActivity.this,
getResources()
.getString(
R.string.login_status_network_or_connection_error),
Toast.LENGTH_SHORT).show();
}
}
};
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate()...");
if (super._onCreate(savedInstanceState)) {
setContentView(R.layout.search);
mNavbar = new NavBar(NavBar.HEADER_STYLE_SEARCH, this);
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
initView();
initSearchSectionList();
refreshSearchSectionList(SearchActivity.LOADING);
doGetSavedSearches();
return true;
} else {
return false;
}
}
private void initView() {
mSearchEdit = (EditText) findViewById(R.id.search_edit);
mSearchEdit.setOnKeyListener(enterKeyHandler);
trendsTitle = (TextView) getLayoutInflater().inflate(
R.layout.search_section_header, null);
trendsTitle.setText(getResources().getString(R.string.trends_title));
savedSearchTitle = (TextView) getLayoutInflater().inflate(
R.layout.search_section_header, null);
savedSearchTitle.setText(getResources().getString(
R.string.saved_search_title));
mSearchSectionAdapter = new MergeAdapter();
mSearchSectionList = (ListView) findViewById(R.id.search_section_list);
mNavbar.getSearchButton().setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
initialQuery = mSearchEdit.getText().toString();
startSearch();
}
});
}
@Override
protected void onResume() {
Log.d(TAG, "onResume()...");
super.onResume();
}
private void doGetSavedSearches() {
if (trendsAndSavedSearchesTask != null
&& trendsAndSavedSearchesTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
trendsAndSavedSearchesTask = new TrendsAndSavedSearchesTask();
trendsAndSavedSearchesTask
.setListener(trendsAndSavedSearchesTaskListener);
trendsAndSavedSearchesTask.setFeedback(mFeedback);
trendsAndSavedSearchesTask.execute();
}
}
private void initSearchSectionList() {
trends = new ArrayList<SearchItem>();
savedSearch = new ArrayList<SearchItem>();
trendsAdapter = new SearchAdapter(this);
savedSearchesAdapter = new SearchAdapter(this);
mSearchSectionAdapter.addView(savedSearchTitle);
mSearchSectionAdapter.addAdapter(savedSearchesAdapter);
mSearchSectionAdapter.addView(trendsTitle);
mSearchSectionAdapter.addAdapter(trendsAdapter);
mSearchSectionList.setAdapter(mSearchSectionAdapter);
}
/**
* 辅助计算位置的类
*
* @author jmx
*
*/
class PositionHelper {
/**
* 返回指定位置属于哪一个小节
*
* @param position
* 绝对位置
* @return 小节的序号,0是第一小节,1是第二小节, -1为无效位置
*/
public int getSectionIndex(int position) {
int[] contentLength = new int[2];
contentLength[0] = savedSearchesAdapter.getCount();
contentLength[1] = trendsAdapter.getCount();
if (position > 0 && position < contentLength[0] + 1) {
return 0;
} else if (position > contentLength[0] + 1
&& position < (contentLength[0] + contentLength[1] + 1) + 1) {
return 1;
} else {
return -1;
}
}
/**
* 返回指定位置在自己所在小节的相对位置
*
* @param position
* 绝对位置
* @return 所在小节的相对位置,-1为无效位置
*/
public int getRelativePostion(int position) {
int[] contentLength = new int[2];
contentLength[0] = savedSearchesAdapter.getCount();
contentLength[1] = trendsAdapter.getCount();
int sectionIndex = getSectionIndex(position);
int offset = 0;
for (int i = 0; i < sectionIndex; ++i) {
offset += contentLength[i] + 1;
}
return position - offset - 1;
}
}
/**
* flag: loading;network error;success
*/
PositionHelper pos_helper = new PositionHelper();
private void refreshSearchSectionList(int flag) {
AdapterView.OnItemClickListener searchSectionListListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
MergeAdapter adapter = (MergeAdapter) (adapterView.getAdapter());
SearchAdapter subAdapter = (SearchAdapter) adapter
.getAdapter(position);
// 计算针对subAdapter中的相对位置
int relativePos = pos_helper.getRelativePostion(position);
SearchItem item = (SearchItem) (subAdapter.getItem(relativePos));
initialQuery = item.query;
startSearch();
}
};
if (flag == SearchActivity.LOADING) {
mSearchSectionList.setOnItemClickListener(null);
savedSearch.clear();
trends.clear();
savedSearchesAdapter.refresh(getString(R.string.search_loading));
trendsAdapter.refresh(getString(R.string.search_loading));
} else if (flag == SearchActivity.NETWORKERROR) {
mSearchSectionList.setOnItemClickListener(null);
savedSearch.clear();
trends.clear();
savedSearchesAdapter
.refresh(getString(R.string.login_status_network_or_connection_error));
trendsAdapter
.refresh(getString(R.string.login_status_network_or_connection_error));
} else {
savedSearchesAdapter.refresh(savedSearch);
trendsAdapter.refresh(trends);
}
if (flag == SearchActivity.SUCCESS) {
mSearchSectionList
.setOnItemClickListener(searchSectionListListener);
}
}
protected boolean startSearch() {
if (!TextUtils.isEmpty(initialQuery)) {
// 以下这个方法在7可用,在8就报空指针
// triggerSearch(initialQuery, null);
Intent i = new Intent(this, SearchResultActivity.class);
i.putExtra(SearchManager.QUERY, initialQuery);
startActivity(i);
} else if (TextUtils.isEmpty(initialQuery)) {
Toast.makeText(this,
getResources().getString(R.string.search_box_null),
Toast.LENGTH_SHORT).show();
return false;
}
return false;
}
// 搜索框回车键判断
private View.OnKeyListener enterKeyHandler = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER
|| keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
if (event.getAction() == KeyEvent.ACTION_UP) {
initialQuery = mSearchEdit.getText().toString();
startSearch();
}
return true;
}
return false;
}
};
private class TrendsAndSavedSearchesTask extends GenericTask {
Trend[] trendsList;
List<SavedSearch> savedSearchsList;
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
trendsList = getApi().getTrends().getTrends();
savedSearchsList = getApi().getSavedSearches();
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
trends.clear();
savedSearch.clear();
for (int i = 0; i < trendsList.length; i++) {
SearchItem item = new SearchItem();
item.name = trendsList[i].getName();
item.query = trendsList[i].getQuery();
trends.add(item);
}
for (int i = 0; i < savedSearchsList.size(); i++) {
SearchItem item = new SearchItem();
item.name = savedSearchsList.get(i).getName();
item.query = savedSearchsList.get(i).getQuery();
savedSearch.add(item);
}
return TaskResult.OK;
}
}
}
class SearchItem {
public String name;
public String query;
}
class SearchAdapter extends BaseAdapter {
protected ArrayList<SearchItem> mSearchList;
private Context mContext;
protected LayoutInflater mInflater;
protected StringBuilder mMetaBuilder;
public SearchAdapter(Context context) {
mSearchList = new ArrayList<SearchItem>();
mContext = context;
mInflater = LayoutInflater.from(mContext);
mMetaBuilder = new StringBuilder();
}
public SearchAdapter(Context context, String prompt) {
this(context);
refresh(prompt);
}
public void refresh(ArrayList<SearchItem> searchList) {
mSearchList = searchList;
notifyDataSetChanged();
}
public void refresh(String prompt) {
SearchItem item = new SearchItem();
item.name = prompt;
item.query = null;
mSearchList.clear();
mSearchList.add(item);
notifyDataSetChanged();
}
@Override
public int getCount() {
return mSearchList.size();
}
@Override
public Object getItem(int position) {
return mSearchList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = mInflater.inflate(R.layout.search_section_view, parent,
false);
TextView text = (TextView) view
.findViewById(R.id.search_section_text);
view.setTag(text);
} else {
view = convertView;
}
TextView text = (TextView) view.getTag();
SearchItem item = mSearchList.get(position);
text.setText(item.name);
return view;
}
}
| Java |
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.fanfou.Query;
import com.ch_linghu.fanfoudroid.fanfou.QueryResult;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.TwitterListBaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.MyListView;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
import com.ch_linghu.fanfoudroid.ui.module.TweetArrayAdapter;
public class SearchResultActivity extends TwitterListBaseActivity implements
MyListView.OnNeedMoreListener {
private static final String TAG = "SearchActivity";
// Views.
private MyListView mTweetList;
// State.
private String mSearchQuery;
private ArrayList<Tweet> mTweets;
private TweetArrayAdapter mAdapter;
private int mNextPage = 1;
private String mLastId = null;
private static class State {
State(SearchResultActivity activity) {
mTweets = activity.mTweets;
mNextPage = activity.mNextPage;
}
public ArrayList<Tweet> mTweets;
public int mNextPage;
}
// Tasks.
private GenericTask mSearchTask;
private TaskListener mSearchTaskListener = new TaskAdapter(){
@Override
public void onPreExecute(GenericTask task) {
if (mNextPage == 1) {
updateProgress(getString(R.string.page_status_refreshing));
} else {
updateProgress(getString(R.string.page_status_refreshing));
}
}
@Override
public void onProgressUpdate(GenericTask task, Object param) {
draw();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
draw();
} else {
// Do nothing.
}
updateProgress("");
}
@Override
public String getName() {
return "SearchTask";
}
};
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)){
Intent intent = getIntent();
// Assume it's SEARCH.
// String action = intent.getAction();
mSearchQuery = intent.getStringExtra(SearchManager.QUERY);
if (TextUtils.isEmpty(mSearchQuery)) {
mSearchQuery = intent.getData().getLastPathSegment();
}
mNavbar.setHeaderTitle(mSearchQuery);
setTitle(mSearchQuery);
State state = (State) getLastNonConfigurationInstance();
if (state != null) {
mTweets = state.mTweets;
draw();
} else {
doSearch();
}
return true;
}else{
return false;
}
}
@Override
protected int getLayoutId(){
return R.layout.main;
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
@Override
public Object onRetainNonConfigurationInstance() {
return createState();
}
private synchronized State createState() {
return new State(this);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mSearchTask != null
&& mSearchTask.getStatus() == GenericTask.Status.RUNNING) {
mSearchTask.cancel(true);
}
super.onDestroy();
}
// UI helpers.
private void updateProgress(String progress) {
mProgressText.setText(progress);
}
@Override
protected void draw() {
mAdapter.refresh(mTweets);
}
private void doSearch() {
Log.d(TAG, "Attempting search.");
if (mSearchTask != null && mSearchTask.getStatus() == GenericTask.Status.RUNNING){
return;
}else{
mSearchTask = new SearchTask();
mSearchTask.setFeedback(mFeedback);
mSearchTask.setListener(mSearchTaskListener);
mSearchTask.execute();
}
}
private class SearchTask extends GenericTask {
ArrayList<Tweet> mTweets = new ArrayList<Tweet>();
@Override
protected TaskResult _doInBackground(TaskParams...params) {
QueryResult result;
try {
Query query = new Query(mSearchQuery);
if (!TextUtils.isEmpty(mLastId)){
query.setMaxId(mLastId);
}
result = getApi().search(query);//.search(mSearchQuery, mNextPage);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
List<com.ch_linghu.fanfoudroid.fanfou.Status> statuses = result.getStatus();
HashSet<String> imageUrls = new HashSet<String>();
publishProgress(SimpleFeedback.calProgressBySize(40, 20, statuses));
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statuses) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Tweet tweet;
tweet = Tweet.create(status);
mLastId = tweet.id;
mTweets.add(tweet);
imageUrls.add(tweet.profileImageUrl);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addTweets(mTweets);
// if (isCancelled()) {
// return TaskResult.CANCELLED;
// }
//
// publishProgress();
//
// // TODO: what if orientation change?
// ImageManager imageManager = getImageManager();
// MemoryImageCache imageCache = new MemoryImageCache();
//
// for (String imageUrl : imageUrls) {
// if (!Utils.isEmpty(imageUrl)) {
// // Fetch image to cache.
// try {
// Bitmap bitmap = imageManager.fetchImage(imageUrl);
// imageCache.put(imageUrl, bitmap);
// } catch (IOException e) {
// Log.e(TAG, e.getMessage(), e);
// }
// }
//
// if (isCancelled()) {
// return TaskResult.CANCELLED;
// }
// }
//
// addImages(imageCache);
return TaskResult.OK;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
public void needMore() {
if (!isLastPage()) {
doSearch();
}
}
public boolean isLastPage() {
return mNextPage == -1;
}
@Override
protected void adapterRefresh() {
mAdapter.refresh(mTweets);
}
private synchronized void addTweets(ArrayList<Tweet> tweets) {
if (tweets.size() == 0) {
mNextPage = -1;
return;
}
mTweets.addAll(tweets);
++mNextPage;
}
@Override
protected String getActivityTitle() {
return mSearchQuery;
}
@Override
protected Tweet getContextItemTweet(int position) {
return (Tweet)mAdapter.getItem(position);
}
@Override
protected TweetAdapter getTweetAdapter() {
return mAdapter;
}
@Override
protected ListView getTweetList() {
return mTweetList;
}
@Override
protected void updateTweet(Tweet tweet) {
// TODO Simple and stupid implementation
for (Tweet t : mTweets){
if (t.id.equals(tweet.id)){
t.favorited = tweet.favorited;
break;
}
}
}
@Override
protected boolean useBasicMenu() {
return true;
}
@Override
protected void setupState() {
mTweets = new ArrayList<Tweet>();
mTweetList = (MyListView) findViewById(R.id.tweet_list);
mAdapter = new TweetArrayAdapter(this);
mTweetList.setAdapter(mAdapter);
mTweetList.setOnNeedMoreListener(this);
}
@Override
public void doRetrieve() {
doSearch();
}
}
| Java |
package com.ch_linghu.fanfoudroid.db;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.util.Log;
import com.ch_linghu.fanfoudroid.data.User;
public final class UserInfoTable implements BaseColumns {
public static final String TAG = "UserInfoTable";
public static final String TABLE_NAME = "userinfo";
public static final String FIELD_USER_NAME = "name";
public static final String FIELD_USER_SCREEN_NAME = "screen_name";
public static final String FIELD_LOCALTION = "location";
public static final String FIELD_DESCRIPTION = "description";
public static final String FIELD_PROFILE_IMAGE_URL = "profile_image_url";
public static final String FIELD_URL = "url";
public static final String FIELD_PROTECTED = "protected";
public static final String FIELD_FOLLOWERS_COUNT = "followers_count";
public static final String FIELD_FRIENDS_COUNT = "friends_count";
public static final String FIELD_FAVORITES_COUNT = "favourites_count";
public static final String FIELD_STATUSES_COUNT = "statuses_count";
public static final String FIELD_LAST_STATUS = "last_status";
public static final String FIELD_CREATED_AT = "created_at";
public static final String FIELD_FOLLOWING = "following";
public static final String FIELD_FOLLOWER_IDS="follower_ids";
public static final String[] TABLE_COLUMNS = new String[] { _ID,
FIELD_USER_NAME, FIELD_USER_SCREEN_NAME,
FIELD_LOCALTION, FIELD_DESCRIPTION,
FIELD_PROFILE_IMAGE_URL, FIELD_URL, FIELD_PROTECTED,
FIELD_FOLLOWERS_COUNT, FIELD_FRIENDS_COUNT,
FIELD_FAVORITES_COUNT, FIELD_STATUSES_COUNT,
FIELD_LAST_STATUS, FIELD_CREATED_AT, FIELD_FOLLOWING};
public static final String CREATE_TABLE = "create table "
+ TABLE_NAME + " ("
+ _ID + " text primary key on conflict replace, "
+ FIELD_USER_NAME + " text not null, "
+ FIELD_USER_SCREEN_NAME + " text, "
+ FIELD_LOCALTION + " text, "
+ FIELD_DESCRIPTION + " text, "
+ FIELD_PROFILE_IMAGE_URL + " text, "
+ FIELD_URL + " text, "
+ FIELD_PROTECTED + " boolean, "
+ FIELD_FOLLOWERS_COUNT + " integer, "
+ FIELD_FRIENDS_COUNT + " integer, "
+ FIELD_FAVORITES_COUNT + " integer, "
+ FIELD_STATUSES_COUNT + " integer, "
+ FIELD_LAST_STATUS + " text, "
+ FIELD_CREATED_AT + " date, "
+ FIELD_FOLLOWING + " boolean "
//+FIELD_FOLLOWER_IDS+" text"
+ ")";
/**
* TODO: 将游标解析为一条用户信息
*
* @param cursor 该方法不会关闭游标
* @return 成功返回User类型的单条数据, 失败返回null
*/
public static User parseCursor(Cursor cursor) {
if (null == cursor || 0 == cursor.getCount()) {
Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty.");
return null;
}
User user = new User();
user.id = cursor.getString(cursor.getColumnIndex(_ID));
user.name = cursor.getString(cursor.getColumnIndex(FIELD_USER_NAME));
user.screenName = cursor.getString(cursor.getColumnIndex(FIELD_USER_SCREEN_NAME));
user.location = cursor.getString(cursor.getColumnIndex(FIELD_LOCALTION));
user.description = cursor.getString(cursor.getColumnIndex(FIELD_DESCRIPTION));
user.profileImageUrl = cursor.getString(cursor.getColumnIndex(FIELD_PROFILE_IMAGE_URL));
user.url = cursor.getString(cursor.getColumnIndex(FIELD_URL));
user.isProtected = (0 == cursor.getInt(cursor.getColumnIndex(FIELD_PROTECTED))) ? false : true;
user.followersCount = cursor.getInt(cursor.getColumnIndex(FIELD_FOLLOWERS_COUNT));
user.lastStatus = cursor.getString(cursor.getColumnIndex(FIELD_LAST_STATUS));
user.friendsCount = cursor.getInt(cursor.getColumnIndex(FIELD_FRIENDS_COUNT));
user.favoritesCount = cursor.getInt(cursor.getColumnIndex(FIELD_FAVORITES_COUNT));
user.statusesCount = cursor.getInt(cursor.getColumnIndex(FIELD_STATUSES_COUNT));
user.isFollowing = (0 == cursor.getInt(cursor.getColumnIndex(FIELD_FOLLOWING))) ? false : true;
//TODO:报空指针异常,待查
// try {
// user.createdAt = StatusDatabase.DB_DATE_FORMATTER.parse(cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_CREATED_AT)));
// } catch (ParseException e) {
// Log.w(TAG, "Invalid created at data.");
// }
return user;
}
} | Java |
package com.ch_linghu.fanfoudroid.db;
import java.text.ParseException;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.util.Log;
import com.ch_linghu.fanfoudroid.data.User;
/**
* Table - Followers
*
*/
public final class FollowTable implements BaseColumns {
public static final String TAG = "FollowTable";
public static final String TABLE_NAME = "followers";
public static final String FIELD_USER_NAME = "name";
public static final String FIELD_USER_SCREEN_NAME = "screen_name";
public static final String FIELD_LOCALTION = "location";
public static final String FIELD_DESCRIPTION = "description";
public static final String FIELD_PROFILE_IMAGE_URL = "profile_image_url";
public static final String FIELD_URL = "url";
public static final String FIELD_PROTECTED = "protected";
public static final String FIELD_FOLLOWERS_COUNT = "followers_count";
public static final String FIELD_FRIENDS_COUNT = "friends_count";
public static final String FIELD_FAVORITES_COUNT = "favourites_count";
public static final String FIELD_STATUSES_COUNT = "statuses_count";
public static final String FIELD_LAST_STATUS = "last_status";
public static final String FIELD_CREATED_AT = "created_at";
public static final String FIELD_FOLLOWING = "following";
public static final String[] TABLE_COLUMNS = new String[] { _ID,
FIELD_USER_NAME, FIELD_USER_SCREEN_NAME,
FIELD_LOCALTION, FIELD_DESCRIPTION,
FIELD_PROFILE_IMAGE_URL, FIELD_URL, FIELD_PROTECTED,
FIELD_FOLLOWERS_COUNT, FIELD_FRIENDS_COUNT,
FIELD_FAVORITES_COUNT, FIELD_STATUSES_COUNT,
FIELD_LAST_STATUS, FIELD_CREATED_AT, FIELD_FOLLOWING};
public static final String CREATE_TABLE = "create table "
+ TABLE_NAME + " ("
+ _ID + " text primary key on conflict replace, "
+ FIELD_USER_NAME + " text not null, "
+ FIELD_USER_SCREEN_NAME + " text, "
+ FIELD_LOCALTION + " text, "
+ FIELD_DESCRIPTION + " text, "
+ FIELD_PROFILE_IMAGE_URL + " text, "
+ FIELD_URL + " text, "
+ FIELD_PROTECTED + " boolean, "
+ FIELD_FOLLOWERS_COUNT + " integer, "
+ FIELD_FRIENDS_COUNT + " integer, "
+ FIELD_FAVORITES_COUNT + " integer, "
+ FIELD_STATUSES_COUNT + " integer, "
+ FIELD_LAST_STATUS + " text, "
+ FIELD_CREATED_AT + " date, "
+ FIELD_FOLLOWING + " boolean "
+ ")";
/**
* TODO: 将游标解析为一条用户信息
*
* @param cursor 该方法不会关闭游标
* @return 成功返回User类型的单条数据, 失败返回null
*/
public static User parseCursor(Cursor cursor) {
if (null == cursor || 0 == cursor.getCount()) {
Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty.");
return null;
}
User user = new User();
user.id = cursor.getString(cursor.getColumnIndex(FollowTable._ID));
user.name = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_USER_NAME));
user.screenName = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_USER_SCREEN_NAME));
user.location = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_LOCALTION));
user.description = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_DESCRIPTION));
user.profileImageUrl = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_PROFILE_IMAGE_URL));
user.url = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_URL));
user.isProtected = (0 == cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_PROTECTED))) ? false : true;
user.followersCount = cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_FOLLOWERS_COUNT));
user.lastStatus = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_LAST_STATUS));;
user.friendsCount = cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_FRIENDS_COUNT));
user.favoritesCount = cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_FAVORITES_COUNT));
user.statusesCount = cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_STATUSES_COUNT));
user.isFollowing = (0 == cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_FOLLOWING))) ? false : true;
try {
user.createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_CREATED_AT)));
} catch (ParseException e) {
Log.w(TAG, "Invalid created at data.");
}
return user;
}
} | Java |
package com.ch_linghu.fanfoudroid.db;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.util.Log;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
/**
* Table - Statuses
* <br /> <br />
* 为节省流量,故此表不保证本地数据库中所有消息具有前后连贯性, 而只确保最新的MAX_ROW_NUM条<br />
* 数据的连贯性, 超出部分则视为垃圾数据, 不再允许读取, 也不保证其是前后连续的.<br />
* <br />
* 因为用户可能中途长时间停止使用本客户端,而换其他客户端(如网页), <br />
* 如果保证本地所有数据的连贯性, 那么就必须自动去下载所有本地缺失的中间数据,<br />
* 而这些数据极有可能是用户通过其他客户端阅读过的无用信息, 浪费了用户流量.<br />
* <br />
* 即认为相对于旧信息而言, 新信息对于用户更为价值, 所以只会新信息进行维护, <br />
* 而旧信息一律视为无用的, 如用户需要查看超过MAX_ROW_NUM的旧数据, 可主动点击, <br />
* 从而请求服务器. 本地只缓存最有价值的MAX条最新信息.<br />
* <br />
* 本地数据库中前MAX_ROW_NUM条的数据模拟一个定长列队, 即在尾部插入N条消息, 就会使得头部<br />
* 的N条消息被标记为垃圾数据(但并不立即收回),只有在认为数据库数据过多时,<br />
* 可手动调用 <code>StatusDatabase.gc(int type)</code> 方法进行垃圾清理.<br />
*
*
*/
public final class StatusTable implements BaseColumns {
public static final String TAG = "StatusTable";
// Status Types
public static final int TYPE_HOME = 1; //首页(我和我的好友)
public static final int TYPE_MENTION = 2; //提到我的
public static final int TYPE_USER = 3; //指定USER的
public static final int TYPE_FAVORITE = 4; //收藏
public static final int TYPE_BROWSE = 5; //随便看看
public static final String TABLE_NAME = "status";
public static final int MAX_ROW_NUM = 20; //单类型数据安全区域
public static final String OWNER_ID = "owner"; //用于标识数据的所有者。以便于处理其他用户的信息(如其他用户的收藏)
public static final String USER_ID = "uid";
public static final String USER_SCREEN_NAME = "screen_name";
public static final String PROFILE_IMAGE_URL = "profile_image_url";
public static final String CREATED_AT = "created_at";
public static final String TEXT = "text";
public static final String SOURCE = "source";
public static final String TRUNCATED = "truncated";
public static final String IN_REPLY_TO_STATUS_ID = "in_reply_to_status_id";
public static final String IN_REPLY_TO_USER_ID = "in_reply_to_user_id";
public static final String IN_REPLY_TO_SCREEN_NAME = "in_reply_to_screen_name";
public static final String FAVORITED = "favorited";
public static final String IS_UNREAD = "is_unread";
public static final String STATUS_TYPE = "status_type";
public static final String PIC_THUMB = "pic_thumbnail";
public static final String PIC_MID = "pic_middle";
public static final String PIC_ORIG = "pic_original";
// private static final String FIELD_PHOTO_URL = "photo_url";
// private double latitude = -1;
// private double longitude = -1;
// private String thumbnail_pic;
// private String bmiddle_pic;
// private String original_pic;
public static final String[] TABLE_COLUMNS = new String[] {_ID, USER_SCREEN_NAME,
TEXT, PROFILE_IMAGE_URL, IS_UNREAD, CREATED_AT,
FAVORITED, IN_REPLY_TO_STATUS_ID, IN_REPLY_TO_USER_ID,
IN_REPLY_TO_SCREEN_NAME, TRUNCATED,
PIC_THUMB, PIC_MID, PIC_ORIG,
SOURCE, USER_ID, STATUS_TYPE, OWNER_ID};
public static final String CREATE_TABLE = "CREATE TABLE "
+ TABLE_NAME + " ("
+ _ID + " text not null,"
+ STATUS_TYPE + " text not null, "
+ OWNER_ID + " text not null, "
+ USER_ID + " text not null, "
+ USER_SCREEN_NAME + " text not null, "
+ TEXT + " text not null, "
+ PROFILE_IMAGE_URL + " text not null, "
+ IS_UNREAD + " boolean not null, "
+ CREATED_AT + " date not null, "
+ SOURCE + " text not null, "
+ FAVORITED + " text, " // TODO : text -> boolean
+ IN_REPLY_TO_STATUS_ID + " text, "
+ IN_REPLY_TO_USER_ID + " text, "
+ IN_REPLY_TO_SCREEN_NAME + " text, "
+ PIC_THUMB + " text, "
+ PIC_MID + " text, "
+ PIC_ORIG + " text, "
+ TRUNCATED + " boolean ,"
+ "PRIMARY KEY (" + _ID + ","+ OWNER_ID + "," + STATUS_TYPE + "))";
/**
* 将游标解析为一条Tweet
*
*
* @param cursor 该方法不会移动或关闭游标
* @return 成功返回 Tweet 类型的单条数据, 失败返回null
*/
public static Tweet parseCursor(Cursor cursor) {
if (null == cursor || 0 == cursor.getCount()) {
Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty.");
return null;
} else if ( -1 == cursor.getPosition() ) {
cursor.moveToFirst();
}
Tweet tweet = new Tweet();
tweet.id = cursor.getString(cursor.getColumnIndex(_ID));
tweet.createdAt = DateTimeHelper.parseDateTimeFromSqlite(cursor.getString(cursor.getColumnIndex(CREATED_AT)));
tweet.favorited = cursor.getString(cursor.getColumnIndex(FAVORITED));
tweet.screenName = cursor.getString(cursor.getColumnIndex(USER_SCREEN_NAME));
tweet.userId = cursor.getString(cursor.getColumnIndex(USER_ID));
tweet.text = cursor.getString(cursor.getColumnIndex(TEXT));
tweet.source = cursor.getString(cursor.getColumnIndex(SOURCE));
tweet.profileImageUrl = cursor.getString(cursor.getColumnIndex(PROFILE_IMAGE_URL));
tweet.inReplyToScreenName = cursor.getString(cursor.getColumnIndex(IN_REPLY_TO_SCREEN_NAME));
tweet.inReplyToStatusId = cursor.getString(cursor.getColumnIndex(IN_REPLY_TO_STATUS_ID));
tweet.inReplyToUserId = cursor.getString(cursor.getColumnIndex(IN_REPLY_TO_USER_ID));
tweet.truncated = cursor.getString(cursor.getColumnIndex(TRUNCATED));
tweet.thumbnail_pic = cursor.getString(cursor.getColumnIndex(PIC_THUMB));
tweet.bmiddle_pic = cursor.getString(cursor.getColumnIndex(PIC_MID));
tweet.original_pic = cursor.getString(cursor.getColumnIndex(PIC_ORIG));
tweet.setStatusType(cursor.getInt(cursor.getColumnIndex(STATUS_TYPE)) );
return tweet;
}
} | Java |
package com.ch_linghu.fanfoudroid.db;
/**
* All information of status table
*
*/
public final class StatusTablesInfo {
} | Java |
package com.ch_linghu.fanfoudroid.db;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.dao.StatusDAO;
import com.ch_linghu.fanfoudroid.data.Dm;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.util.DebugTimer;
/**
* A Database which contains all statuses and direct-messages, use
* getInstane(Context) to get a new instance
*
*/
public class TwitterDatabase {
private static final String TAG = "TwitterDatabase";
private static final String DATABASE_NAME = "status_db";
private static final int DATABASE_VERSION = 1;
private static TwitterDatabase instance = null;
private static DatabaseHelper mOpenHelper = null;
private Context mContext = null;
/**
* SQLiteOpenHelper
*
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
// Construct
public DatabaseHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
public DatabaseHelper(Context context, String name) {
this(context, name, DATABASE_VERSION);
}
public DatabaseHelper(Context context) {
this(context, DATABASE_NAME, DATABASE_VERSION);
}
public DatabaseHelper(Context context, int version) {
this(context, DATABASE_NAME, null, version);
}
public DatabaseHelper(Context context, String name, int version) {
this(context, name, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "Create Database.");
// Log.d(TAG, StatusTable.STATUS_TABLE_CREATE);
db.execSQL(StatusTable.CREATE_TABLE);
db.execSQL(MessageTable.CREATE_TABLE);
db.execSQL(FollowTable.CREATE_TABLE);
//2011.03.01 add beta
db.execSQL(UserInfoTable.CREATE_TABLE);
}
@Override
public synchronized void close() {
Log.d(TAG, "Close Database.");
super.close();
}
@Override
public void onOpen(SQLiteDatabase db) {
Log.d(TAG, "Open Database.");
super.onOpen(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "Upgrade Database.");
dropAllTables(db);
}
private void dropAllTables(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + StatusTable.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + MessageTable.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + FollowTable.TABLE_NAME);
//2011.03.01 add
db.execSQL("DROP TABLE IF EXISTS "+UserInfoTable.TABLE_NAME);
}
}
private TwitterDatabase(Context context) {
mContext = context;
mOpenHelper = new DatabaseHelper(context);
}
public static synchronized TwitterDatabase getInstance(Context context) {
if (null == instance) {
return new TwitterDatabase(context);
}
return instance;
}
// 测试用
public SQLiteOpenHelper getSQLiteOpenHelper() {
return mOpenHelper;
}
public static SQLiteDatabase getDb(boolean writeable) {
if (writeable) {
return mOpenHelper.getWritableDatabase();
} else {
return mOpenHelper.getReadableDatabase();
}
}
public void close() {
if (null != instance) {
mOpenHelper.close();
instance = null;
}
}
/**
* 清空所有表中数据, 谨慎使用
*
*/
public void clearData() {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.execSQL("DELETE FROM " + StatusTable.TABLE_NAME);
db.execSQL("DELETE FROM " + MessageTable.TABLE_NAME);
db.execSQL("DELETE FROM " + FollowTable.TABLE_NAME);
//2011.03.01 add
db.execSQL("DELETE FROM "+UserInfoTable.TABLE_NAME);
}
/**
* 直接删除数据库文件, 调试用
*
* @return true if this file was deleted, false otherwise.
* @deprecated
*/
private boolean deleteDatabase() {
File dbFile = mContext.getDatabasePath(DATABASE_NAME);
return dbFile.delete();
}
/**
* 取出某类型的一条消息
*
* @param tweetId
* @param type of status
* <li>StatusTable.TYPE_HOME</li>
* <li>StatusTable.TYPE_MENTION</li>
* <li>StatusTable.TYPE_USER</li>
* <li>StatusTable.TYPE_FAVORITE</li>
* <li>-1 means all types</li>
* @return 将Cursor转换过的Tweet对象
* @deprecated use StatusDAO#findStatus()
*/
public Tweet queryTweet(String tweetId, int type) {
SQLiteDatabase Db = mOpenHelper.getWritableDatabase();
String selection = StatusTable._ID + "=? ";
if (-1 != type) {
selection += " AND " + StatusTable.STATUS_TYPE + "=" + type;
}
Cursor cursor = Db.query(StatusTable.TABLE_NAME,
StatusTable.TABLE_COLUMNS, selection, new String[] { tweetId },
null, null, null);
Tweet tweet = null;
if (cursor != null) {
cursor.moveToFirst();
if (cursor.getCount() > 0) {
tweet = StatusTable.parseCursor(cursor);
}
}
cursor.close();
return tweet;
}
/**
* 快速检查某条消息是否存在(指定类型)
*
* @param tweetId
* @param type
* <li>StatusTable.TYPE_HOME</li>
* <li>StatusTable.TYPE_MENTION</li>
* <li>StatusTable.TYPE_USER</li>
* <li>StatusTable.TYPE_FAVORITE</li>
* @return is exists
* @deprecated use StatusDAO#isExists()
*/
public boolean isExists(String tweetId, String owner, int type) {
SQLiteDatabase Db = mOpenHelper.getWritableDatabase();
boolean result = false;
Cursor cursor = Db.query(StatusTable.TABLE_NAME,
new String[] { StatusTable._ID }, StatusTable._ID + " =? AND "
+ StatusTable.OWNER_ID + "=? AND "
+ StatusTable.STATUS_TYPE + " = " + type,
new String[] { tweetId, owner }, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
result = true;
}
cursor.close();
return result;
}
/**
* 删除一条消息
*
* @param tweetId
* @param type -1 means all types
* @return the number of rows affected if a whereClause is passed in, 0
* otherwise. To remove all rows and get a count pass "1" as the
* whereClause.
* @deprecated use {@link StatusDAO#deleteStatus(String, String, int)}
*/
public int deleteTweet(String tweetId, String owner, int type) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
String where = StatusTable._ID + " =? ";
if (!TextUtils.isEmpty(owner)){
where += " AND " + StatusTable.OWNER_ID + " = '" + owner + "' ";
}
if (-1 != type) {
where += " AND " + StatusTable.STATUS_TYPE + " = " + type;
}
return db.delete(StatusTable.TABLE_NAME, where, new String[] { tweetId });
}
/**
* 删除超过MAX_ROW_NUM垃圾数据
*
* @param type
* <li>StatusTable.TYPE_HOME</li>
* <li>StatusTable.TYPE_MENTION</li>
* <li>StatusTable.TYPE_USER</li>
* <li>StatusTable.TYPE_FAVORITE</li>
* <li>-1 means all types</li>
*/
public void gc(String owner, int type) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
String sql = "DELETE FROM " + StatusTable.TABLE_NAME
+ " WHERE " + StatusTable._ID + " NOT IN "
+ " (SELECT " + StatusTable._ID // 子句
+ " FROM " + StatusTable.TABLE_NAME;
boolean first = true;
if (!TextUtils.isEmpty(owner)){
sql += " WHERE " + StatusTable.OWNER_ID + " = '" + owner + "' ";
first = false;
}
if (type != -1){
if (first){
sql += " WHERE ";
}else{
sql += " AND ";
}
sql += StatusTable.STATUS_TYPE + " = " + type + " ";
}
sql += " ORDER BY " + StatusTable.CREATED_AT + " DESC LIMIT "
+ StatusTable.MAX_ROW_NUM + ")";
if (!TextUtils.isEmpty(owner)){
sql += " AND " + StatusTable.OWNER_ID + " = '" + owner + "' ";
}
if (type != -1) {
sql += " AND " + StatusTable.STATUS_TYPE + " = " + type + " ";
}
Log.v(TAG, sql);
mDb.execSQL(sql);
}
public final static DateFormat DB_DATE_FORMATTER = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
private static final int CONFLICT_REPLACE = 0x00000005;
/**
* 向Status表中写入一行数据, 此方法为私有方法, 外部插入数据请使用 putTweets()
*
* @param tweet
* 需要写入的单条消息
* @return the row ID of the newly inserted row, or -1 if an error occurred
* @deprecated use {@link StatusDAO#insertStatus(Status, boolean)}
*/
public long insertTweet(Tweet tweet, String owner, int type, boolean isUnread) {
SQLiteDatabase Db = mOpenHelper.getWritableDatabase();
if (isExists(tweet.id, owner, type)) {
Log.w(TAG, tweet.id + "is exists.");
return -1;
}
ContentValues initialValues = makeTweetValues(tweet, owner, type, isUnread);
long id = Db.insert(StatusTable.TABLE_NAME, null, initialValues);
if (-1 == id) {
Log.e(TAG, "cann't insert the tweet : " + tweet.toString());
} else {
//Log.v(TAG, "Insert a status into database : " + tweet.toString());
}
return id;
}
/**
* 更新一条消息
*
* @param tweetId
* @param values
* ContentValues 需要更新字段的键值对
* @return the number of rows affected
* @deprecated use {@link StatusDAO#updateStatus(String, ContentValues)}
*/
public int updateTweet(String tweetId, ContentValues values) {
Log.v(TAG, "Update Tweet : " + tweetId + " " + values.toString());
SQLiteDatabase Db = mOpenHelper.getWritableDatabase();
return Db.update(StatusTable.TABLE_NAME, values,
StatusTable._ID + "=?", new String[] { tweetId });
}
/** @deprecated */
private ContentValues makeTweetValues(Tweet tweet, String owner, int type, boolean isUnread) {
// 插入一条新消息
ContentValues initialValues = new ContentValues();
initialValues.put(StatusTable.OWNER_ID, owner);
initialValues.put(StatusTable.STATUS_TYPE, type);
initialValues.put(StatusTable._ID, tweet.id);
initialValues.put(StatusTable.TEXT, tweet.text);
initialValues.put(StatusTable.USER_ID, tweet.userId);
initialValues.put(StatusTable.USER_SCREEN_NAME, tweet.screenName);
initialValues.put(StatusTable.PROFILE_IMAGE_URL,
tweet.profileImageUrl);
initialValues.put(StatusTable.PIC_THUMB, tweet.thumbnail_pic);
initialValues.put(StatusTable.PIC_MID, tweet.bmiddle_pic);
initialValues.put(StatusTable.PIC_ORIG, tweet.original_pic);
initialValues.put(StatusTable.FAVORITED, tweet.favorited);
initialValues.put(StatusTable.IN_REPLY_TO_STATUS_ID,
tweet.inReplyToStatusId);
initialValues.put(StatusTable.IN_REPLY_TO_USER_ID,
tweet.inReplyToUserId);
initialValues.put(StatusTable.IN_REPLY_TO_SCREEN_NAME,
tweet.inReplyToScreenName);
// initialValues.put(FIELD_IS_REPLY, tweet.isReply());
initialValues.put(StatusTable.CREATED_AT,
DB_DATE_FORMATTER.format(tweet.createdAt));
initialValues.put(StatusTable.SOURCE, tweet.source);
initialValues.put(StatusTable.IS_UNREAD, isUnread);
initialValues.put(StatusTable.TRUNCATED, tweet.truncated);
// TODO: truncated
return initialValues;
}
/**
* 写入N条消息
*
* @param tweets
* 需要写入的消息List
* @return
* 写入的记录条数
*/
public int putTweets(List<Tweet> tweets, String owner, int type, boolean isUnread) {
if (TwitterApplication.DEBUG){
DebugTimer.betweenStart("Status DB");
}
if (null == tweets || 0 == tweets.size())
{
return 0;
}
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int result = 0;
try {
db.beginTransaction();
for (int i = tweets.size() - 1; i >= 0; i--) {
Tweet tweet = tweets.get(i);
ContentValues initialValues = makeTweetValues(tweet, owner, type, isUnread);
long id = db.insert(StatusTable.TABLE_NAME, null, initialValues);
if (-1 == id) {
Log.e(TAG, "cann't insert the tweet : " + tweet.toString());
} else {
++result;
//Log.v(TAG, String.format("Insert a status into database[%s] : %s", owner, tweet.toString()));
Log.v("TAG", "Insert Status");
}
}
// gc(type); // 保持总量
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
if (TwitterApplication.DEBUG){
DebugTimer.betweenEnd("Status DB");
}
return result;
}
/**
* 取出指定用户的某一类型的所有消息
*
* @param userId
* @param tableName
* @return a cursor
* @deprecated use {@link StatusDAO#findStatuses(String, int)}
*/
public Cursor fetchAllTweets(String owner, int type) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
return mDb.query(StatusTable.TABLE_NAME, StatusTable.TABLE_COLUMNS,
StatusTable.OWNER_ID + " = ? AND " + StatusTable.STATUS_TYPE + " = " + type,
new String[]{owner}, null, null,
StatusTable.CREATED_AT + " DESC ");
//LIMIT " + StatusTable.MAX_ROW_NUM);
}
/**
* 取出自己的某一类型的所有消息
*
* @param tableName
* @return a cursor
*/
public Cursor fetchAllTweets(int type) {
// 获取登录用户id
SharedPreferences preferences = TwitterApplication.mPref;
String myself = preferences.getString(Preferences.CURRENT_USER_ID,
TwitterApplication.mApi.getUserId());
return fetchAllTweets(myself, type);
}
/**
* 清空某类型的所有信息
*
* @param tableName
* @return the number of rows affected if a whereClause is passed in, 0
* otherwise. To remove all rows and get a count pass "1" as the
* whereClause.
*/
public int dropAllTweets(int type) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
return mDb.delete(StatusTable.TABLE_NAME, StatusTable.STATUS_TYPE
+ " = " + type, null);
}
/**
* 取出本地某类型最新消息ID
*
* @param type
* @return The newest Status Id
*/
public String fetchMaxTweetId(String owner, int type) {
return fetchMaxOrMinTweetId(owner, type, true);
}
/**
* 取出本地某类型最旧消息ID
*
* @param tableName
* @return The oldest Status Id
*/
public String fetchMinTweetId(String owner, int type) {
return fetchMaxOrMinTweetId(owner, type, false);
}
private String fetchMaxOrMinTweetId(String owner, int type, boolean isMax) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
String sql = "SELECT " + StatusTable._ID + " FROM "
+ StatusTable.TABLE_NAME + " WHERE "
+ StatusTable.STATUS_TYPE + " = " + type + " AND "
+ StatusTable.OWNER_ID + " = '" + owner + "' "
+ " ORDER BY "
+ StatusTable.CREATED_AT;
if (isMax)
sql += " DESC ";
Cursor mCursor = mDb.rawQuery(sql + " LIMIT 1", null);
String result = null;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
if (mCursor.getCount() == 0) {
result = null;
} else {
result = mCursor.getString(0);
}
mCursor.close();
return result;
}
/**
* Count unread tweet
*
* @param tableName
* @return
*/
public int fetchUnreadCount(String owner, int type) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + StatusTable._ID + ")"
+ " FROM " + StatusTable.TABLE_NAME + " WHERE "
+ StatusTable.STATUS_TYPE + " = " + type + " AND "
+ StatusTable.OWNER_ID + " = '" + owner + "' AND "
+ StatusTable.IS_UNREAD + " = 1 ",
// "LIMIT " + StatusTable.MAX_ROW_NUM,
null);
int result = 0;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
result = mCursor.getInt(0);
mCursor.close();
return result;
}
public int addNewTweetsAndCountUnread(List<Tweet> tweets, String owner, int type) {
putTweets(tweets, owner, type, true);
return fetchUnreadCount(owner, type);
}
/**
* Set isFavorited
*
* @param tweetId
* @param isFavorited
* @return Is Succeed
* @deprecated use {@link Status#setFavorited(boolean)} and
* {@link StatusDAO#updateStatus(Status)}
*/
public boolean setFavorited(String tweetId, String isFavorited) {
ContentValues values = new ContentValues();
values.put(StatusTable.FAVORITED, isFavorited);
int i = updateTweet(tweetId, values);
return (i > 0) ? true : false;
}
// DM & Follower
/**
* 写入一条私信
*
* @param dm
* @param isUnread
* @return the row ID of the newly inserted row, or -1 if an error occurred,
* 因为主键的原因,此处返回的不是 _ID 的值, 而是一个自增长的 row_id
*/
public long createDm(Dm dm, boolean isUnread) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(MessageTable._ID, dm.id);
initialValues.put(MessageTable.FIELD_USER_SCREEN_NAME, dm.screenName);
initialValues.put(MessageTable.FIELD_TEXT, dm.text);
initialValues.put(MessageTable.FIELD_PROFILE_IMAGE_URL,
dm.profileImageUrl);
initialValues.put(MessageTable.FIELD_IS_UNREAD, isUnread);
initialValues.put(MessageTable.FIELD_IS_SENT, dm.isSent);
initialValues.put(MessageTable.FIELD_CREATED_AT,
DB_DATE_FORMATTER.format(dm.createdAt));
initialValues.put(MessageTable.FIELD_USER_ID, dm.userId);
return mDb.insert(MessageTable.TABLE_NAME, null, initialValues);
}
//
/**
* Create a follower
*
* @param userId
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long createFollower(String userId) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(FollowTable._ID, userId);
long rowId = mDb.insert(FollowTable.TABLE_NAME, null, initialValues);
if (-1 == rowId) {
Log.e(TAG, "Cann't create Follower : " + userId);
} else {
Log.v(TAG, "Success create follower : " + userId);
}
return rowId;
}
/**
* 清空Followers表并添加新内容
*
* @param followers
*/
public void syncFollowers(List<String> followers) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
try {
mDb.beginTransaction();
boolean result = deleteAllFollowers();
Log.v(TAG, "Result of DeleteAllFollowers: " + result);
for (String userId : followers) {
createFollower(userId);
}
mDb.setTransactionSuccessful();
} finally {
mDb.endTransaction();
}
}
/**
* @param type
* <li>MessageTable.TYPE_SENT</li>
* <li>MessageTable.TYPE_GET</li>
* <li>其他任何值都认为取出所有类型</li>
* @return
*/
public Cursor fetchAllDms(int type) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
String selection = null;
if (MessageTable.TYPE_SENT == type) {
selection = MessageTable.FIELD_IS_SENT + " = "
+ MessageTable.TYPE_SENT;
} else if (MessageTable.TYPE_GET == type) {
selection = MessageTable.FIELD_IS_SENT + " = "
+ MessageTable.TYPE_GET;
}
return mDb.query(MessageTable.TABLE_NAME, MessageTable.TABLE_COLUMNS,
selection, null, null, null, MessageTable.FIELD_CREATED_AT
+ " DESC");
}
public Cursor fetchInboxDms() {
return fetchAllDms(MessageTable.TYPE_GET);
}
public Cursor fetchSendboxDms() {
return fetchAllDms(MessageTable.TYPE_SENT);
}
public Cursor fetchAllFollowers() {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
return mDb.query(FollowTable.TABLE_NAME, FollowTable.TABLE_COLUMNS,
null, null, null, null, null);
}
/**
* FIXME:
* @param filter
* @return
*/
public Cursor getFollowerUsernames(String filter) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
String likeFilter = '%' + filter + '%';
// FIXME: 此方法的作用应该是在于在写私信时自动完成联系人的功能,
// 改造数据库后,因为本地tweets表中的数据有限, 所以几乎使得该功能没有实际价值(因为能从数据库中读到的联系人很少)
// 在完成关注者/被关注者两个界面后, 看能不能使得本地有一份
// [互相关注] 的 id/name 缓存(即getFriendsIds和getFollowersIds的交集, 因为客户端只能给他们发私信, 如果按现在
// 只提示followers的列表则很容易造成服务器返回"只能给互相关注的人发私信"的错误信息, 这会造成用户无法理解, 因为此联系人是我们提供给他们选择的,
// 并且将目前的自动完成功能的基础上加一个[选择联系人]按钮, 用于启动一个新的联系人列表页面以显示所有可发送私信的联系人对象, 类似手机写短信时的选择联系人功能
return null;
// FIXME: clean this up. 新数据库中失效, 表名, 列名
// return mDb.rawQuery(
// "SELECT user_id AS _id, user"
// + " FROM (SELECT user_id, user FROM tweets"
// + " INNER JOIN followers on tweets.user_id = followers._id UNION"
// + " SELECT user_id, user FROM dms INNER JOIN followers"
// + " on dms.user_id = followers._id)"
// + " WHERE user LIKE ?"
// + " ORDER BY user COLLATE NOCASE",
// new String[] { likeFilter });
}
/**
* @param userId
* 该用户是否follow Me
* @deprecated 未使用
* @return
*/
public boolean isFollower(String userId) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor cursor = mDb.query(FollowTable.TABLE_NAME,
FollowTable.TABLE_COLUMNS, FollowTable._ID + "= ?",
new String[] { userId }, null, null, null);
boolean result = false;
if (cursor != null && cursor.moveToFirst()) {
result = true;
}
cursor.close();
return result;
}
public boolean deleteAllFollowers() {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
return mDb.delete(FollowTable.TABLE_NAME, null, null) > 0;
}
public boolean deleteDm(String id) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
return mDb.delete(MessageTable.TABLE_NAME,
String.format("%s = '%s'", MessageTable._ID, id), null) > 0;
}
/**
* @param tableName
* @return the number of rows affected
*/
public int markAllTweetsRead(String owner, int type) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(StatusTable.IS_UNREAD, 0);
return mDb.update(StatusTable.TABLE_NAME, values,
StatusTable.STATUS_TYPE + "=" + type, null);
}
public boolean deleteAllDms() {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
return mDb.delete(MessageTable.TABLE_NAME, null, null) > 0;
}
public int markAllDmsRead() {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(MessageTable.FIELD_IS_UNREAD, 0);
return mDb.update(MessageTable.TABLE_NAME, values, null, null);
}
public String fetchMaxDmId(boolean isSent) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor mCursor = mDb.rawQuery("SELECT " + MessageTable._ID + " FROM "
+ MessageTable.TABLE_NAME + " WHERE "
+ MessageTable.FIELD_IS_SENT + " = ? " + " ORDER BY "
+ MessageTable.FIELD_CREATED_AT + " DESC LIMIT 1",
new String[] { isSent ? "1" : "0" });
String result = null;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
if (mCursor.getCount() == 0) {
result = null;
} else {
result = mCursor.getString(0);
}
mCursor.close();
return result;
}
public int addNewDmsAndCountUnread(List<Dm> dms) {
addDms(dms, true);
return fetchUnreadDmCount();
}
public int fetchDmCount() {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + MessageTable._ID
+ ") FROM " + MessageTable.TABLE_NAME, null);
int result = 0;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
result = mCursor.getInt(0);
mCursor.close();
return result;
}
private int fetchUnreadDmCount() {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + MessageTable._ID
+ ") FROM " + MessageTable.TABLE_NAME + " WHERE "
+ MessageTable.FIELD_IS_UNREAD + " = 1", null);
int result = 0;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
result = mCursor.getInt(0);
mCursor.close();
return result;
}
public void addDms(List<Dm> dms, boolean isUnread) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
try {
mDb.beginTransaction();
for (Dm dm : dms) {
createDm(dm, isUnread);
}
// limitRows(TABLE_DIRECTMESSAGE, TwitterApi.RETRIEVE_LIMIT);
mDb.setTransactionSuccessful();
} finally {
mDb.endTransaction();
}
}
//2011.03.01 add
//UserInfo操作
public Cursor getAllUserInfo(){
SQLiteDatabase mDb=mOpenHelper.getReadableDatabase();
return mDb.query(UserInfoTable.TABLE_NAME,UserInfoTable.TABLE_COLUMNS, null, null, null, null, null);
}
/**
* 根据id列表获取user数据
* @param userIds
* @return
*/
public Cursor getUserInfoByIds(String[] userIds){
SQLiteDatabase mDb=mOpenHelper.getReadableDatabase();
String userIdStr="";
for(String id:userIds){
userIdStr+="'"+id+"',";
}
if(userIds.length==0){
userIdStr="'',";
}
userIdStr=userIdStr.substring(0, userIdStr.lastIndexOf(","));//删除最后的逗号
return mDb.query(UserInfoTable.TABLE_NAME, UserInfoTable.TABLE_COLUMNS, UserInfoTable._ID+" in ("+userIdStr+")", null, null, null, null);
}
/**
* 新建用户
*
* @param user
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long createUserInfo(com.ch_linghu.fanfoudroid.data.User user) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(UserInfoTable._ID, user.id);
initialValues.put(UserInfoTable.FIELD_USER_NAME, user.name);
initialValues.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.screenName);
initialValues.put(UserInfoTable.FIELD_LOCALTION, user.location);
initialValues.put(UserInfoTable.FIELD_DESCRIPTION, user.description);
initialValues.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user.profileImageUrl);
initialValues.put(UserInfoTable.FIELD_URL, user.url);
initialValues.put(UserInfoTable.FIELD_PROTECTED, user.isProtected);
initialValues.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.followersCount);
initialValues.put(UserInfoTable.FIELD_LAST_STATUS, user.lastStatus);
initialValues.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.friendsCount);
initialValues.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.favoritesCount);
initialValues.put(UserInfoTable.FIELD_STATUSES_COUNT, user.statusesCount);
initialValues.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing);
//long rowId = mDb.insertWithOnConflict(UserInfoTable.TABLE_NAME, null, initialValues,SQLiteDatabase.CONFLICT_REPLACE);
long rowId = insertWithOnConflict(mDb, UserInfoTable.TABLE_NAME, null, initialValues, CONFLICT_REPLACE);
if (-1 == rowId) {
Log.e(TAG, "Cann't create user : " + user.id);
} else {
Log.v(TAG, "create create user : " + user.id);
}
return rowId;
}
//SQLiteDatabase.insertWithConflict是LEVEL 8(2.2)才引入的新方法
//为了兼容旧版,这里给出一个简化的兼容实现
//要注意的是这个实现和标准的函数行为并不完全一致
private long insertWithOnConflict(SQLiteDatabase db, String tableName,
String nullColumnHack, ContentValues initialValues, int conflictReplace) {
long rowId = db.insert(tableName, nullColumnHack, initialValues);
if(-1 == rowId){
//尝试update
rowId = db.update(tableName, initialValues,
UserInfoTable._ID+"="+initialValues.getAsString(UserInfoTable._ID), null);
}
return rowId;
}
public long createWeiboUserInfo(com.ch_linghu.fanfoudroid.fanfou.User user){
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues args = new ContentValues();
args.put(UserInfoTable._ID, user.getId());
args.put(UserInfoTable.FIELD_USER_NAME, user.getName());
args.put(UserInfoTable.FIELD_USER_SCREEN_NAME,
user.getScreenName());
String location = user.getLocation();
args.put(UserInfoTable.FIELD_LOCALTION, location);
String description = user.getDescription();
args.put(UserInfoTable.FIELD_DESCRIPTION, description);
args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL,
user.getProfileImageURL().toString());
if (user.getURL() != null) {
args.put(UserInfoTable.FIELD_URL, user.getURL().toString());
}
args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected());
args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT,
user.getFollowersCount());
args.put(UserInfoTable.FIELD_LAST_STATUS, user.getStatusSource());
args.put(UserInfoTable.FIELD_FRIENDS_COUNT,
user.getFriendsCount());
args.put(UserInfoTable.FIELD_FAVORITES_COUNT,
user.getFavouritesCount());
args.put(UserInfoTable.FIELD_STATUSES_COUNT,
user.getStatusesCount());
args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing());
//long rowId = mDb.insert(UserInfoTable.TABLE_NAME, null, args);
//省去判断existUser,如果存在数据则replace
//long rowId=mDb.insertWithOnConflict(UserInfoTable.TABLE_NAME, null, args, SQLiteDatabase.CONFLICT_REPLACE);
long rowId=insertWithOnConflict(mDb, UserInfoTable.TABLE_NAME, null, args, CONFLICT_REPLACE);
if (-1 == rowId) {
Log.e(TAG, "Cann't createWeiboUserInfo : " + user.getId());
} else {
Log.v(TAG, "create createWeiboUserInfo : " + user.getId());
}
return rowId;
}
/**
* 查看数据是否已保存用户数据
* @param userId
* @return
*/
public boolean existsUser(String userId) {
SQLiteDatabase Db = mOpenHelper.getReadableDatabase();
boolean result = false;
Cursor cursor = Db.query(UserInfoTable.TABLE_NAME,
new String[] { UserInfoTable._ID }, UserInfoTable._ID +"='"+userId+"'",
null, null, null, null);
Log.v("testesetesteste", String.valueOf(cursor.getCount()));
if (cursor != null && cursor.getCount() > 0) {
result = true;
}
cursor.close();
return result;
}
/**
* 根据userid提取信息
* @param userId
* @return
*/
public Cursor getUserInfoById(String userId){
SQLiteDatabase Db = mOpenHelper.getReadableDatabase();
Cursor cursor = Db.query(UserInfoTable.TABLE_NAME,
UserInfoTable.TABLE_COLUMNS, UserInfoTable._ID + " = '" +userId+"'",
null, null, null, null);
return cursor;
}
/**
* 更新用户
* @param uid
* @param args
* @return
*/
public boolean updateUser(String uid,ContentValues args){
SQLiteDatabase Db=mOpenHelper.getWritableDatabase();
return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID+"='"+uid+"'", null)>0;
}
/**
* 更新用户信息
*/
public boolean updateUser(com.ch_linghu.fanfoudroid.data.User user){
SQLiteDatabase Db=mOpenHelper.getWritableDatabase();
ContentValues args=new ContentValues();
args.put(UserInfoTable._ID, user.id);
args.put(UserInfoTable.FIELD_USER_NAME, user.name);
args.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.screenName);
args.put(UserInfoTable.FIELD_LOCALTION, user.location);
args.put(UserInfoTable.FIELD_DESCRIPTION, user.description);
args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user.profileImageUrl);
args.put(UserInfoTable.FIELD_URL, user.url);
args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected);
args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.followersCount);
args.put(UserInfoTable.FIELD_LAST_STATUS, user.lastStatus);
args.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.friendsCount);
args.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.favoritesCount);
args.put(UserInfoTable.FIELD_STATUSES_COUNT, user.statusesCount);
args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing);
return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID+"='"+user.id+"'", null)>0;
}
/**
* 减少转换的开销
* @param user
* @return
*/
public boolean updateWeiboUser(com.ch_linghu.fanfoudroid.fanfou.User user){
SQLiteDatabase Db=mOpenHelper.getWritableDatabase();
ContentValues args = new ContentValues();
args.put(UserInfoTable._ID, user.getName());
args.put(UserInfoTable.FIELD_USER_NAME, user.getName());
args.put(UserInfoTable.FIELD_USER_SCREEN_NAME,
user.getScreenName());
String location = user.getLocation();
args.put(UserInfoTable.FIELD_LOCALTION, location);
String description = user.getDescription();
args.put(UserInfoTable.FIELD_DESCRIPTION, description);
args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL,
user.getProfileImageURL().toString());
if (user.getURL() != null) {
args.put(UserInfoTable.FIELD_URL, user.getURL().toString());
}
args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected());
args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT,
user.getFollowersCount());
args.put(UserInfoTable.FIELD_LAST_STATUS, user.getStatusSource());
args.put(UserInfoTable.FIELD_FRIENDS_COUNT,
user.getFriendsCount());
args.put(UserInfoTable.FIELD_FAVORITES_COUNT,
user.getFavouritesCount());
args.put(UserInfoTable.FIELD_STATUSES_COUNT,
user.getStatusesCount());
args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing());
return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID+"='"+user.getId()+"'", null)>0;
}
/**
* 同步用户,更新已存在的用户,插入未存在的用户
*/
public void syncUsers(List<com.ch_linghu.fanfoudroid.data.User> users){
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
try{
mDb.beginTransaction();
for(com.ch_linghu.fanfoudroid.data.User u:users){
// if(existsUser(u.id)){
// updateUser(u);
// }else{
// createUserInfo(u);
// }
createUserInfo(u);
}
mDb.setTransactionSuccessful();
} finally {
mDb.endTransaction();
}
}
public void syncWeiboUsers(List<com.ch_linghu.fanfoudroid.fanfou.User> users) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
try {
mDb.beginTransaction();
for (com.ch_linghu.fanfoudroid.fanfou.User u : users) {
// if (existsUser(u.getId())) {
// updateWeiboUser(u);
// } else {
// createWeiboUserInfo(u);
// }
createWeiboUserInfo(u);
}
mDb.setTransactionSuccessful();
} finally {
mDb.endTransaction();
}
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.