How to get mysql data into listview in android - android

I Want to get data from mysql table in listview. i want to show that data in listview below my calander. can any one help me in simple manner. i have search lot for this but i didn't found proper solution. here is my code. help will be appreciated.
public class ActionList extends ListActivity {
public static String date;
public static String custname;
public static String starttime;
public static String endtime;
public static String task;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actionlist);
Button plusBtn = (Button) findViewById(R.id.plusBtn);
Button buttonLogout = (Button) findViewById(R.id.btnLogout);
LoginActivity dao = new LoginActivity();
try {
Statement stmt = dao.dbConnection().createStatement();
String sql = "select * from task_tab";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println("This Is rs DAta "
+ rs.getString(1).toString());
date = rs.getString(2).toString();
task = rs.getString(3).toString();
custname = rs.getString(5).toString();
starttime = rs.getString(8).toString();
endtime = rs.getString(9).toString();
}
String[] list2 = { date, task, custname, starttime, endtime };
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list2));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
plusBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent listActivityIntent = new Intent(ActionList.this,
CalendarView.class);
ActionList.this.startActivity(listActivityIntent);
}
});
buttonLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
LoginActivity.class);
intent.putExtra("LoginMessage", "Logged Out");
startActivity(intent);
removeDialog(0);
}
});
}

Related

App stops whenever I press back button

Problem: This only happening on some pages. when I press back app stops. I get this error. I am not able to figure it out the exact problem. I am new to android. and this is happening at many pages.Any help would be highly appreciated.
logcat error:
InputEventSender:Exception dispatching finished signal.E/MessageQueue-JNI:Exception in MessageQueue callback:handleReceiveCallbackE/MessageQueue-JNI:java.lang.NullPointerException: Attempt to invoke virtual method 'void android.database.sqlite.SQLiteDatabase.close()' on a null object reference at twik.in.DBHelper.close(DBHelper.java:102)at twik.in.ActivityMenuDetail.onBackPressed(ActivityMenuDetail.java:285)at android.app.Activity.onKeyUp(Activity.java:2477)at android.view.KeyEvent.dispatch(KeyEvent.java:2664)at android.app.Activity.dispatchKeyEvent(Activity.java:2730)
In error these two classes are mentioned so I am posting its code here
public class ActivityMenuDetail extends Activity {
ImageView imgPreview;
TextView txtText, txtSubText;
WebView txtDescription;
Button btnAdd;
ScrollView sclDetail;
ProgressBar prgLoading;
TextView txtAlert;
// declare dbhelper object
static DBHelper dbhelper;
// declare ImageLoader object
ImageLoader imageLoader;
// declare variables to store menu data
String Menu_image, Menu_name, Menu_serve, Menu_description;
double Menu_price;
int Menu_quantity;
long Menu_ID;
String MenuDetailAPI;
int IOConnect = 0;
// create price format
DecimalFormat formatData = new DecimalFormat("#.##");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_detail);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.header)));
bar.setTitle("Service Centre Detail");
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
txtText = (TextView) findViewById(R.id.txtText);
txtSubText = (TextView) findViewById(R.id.txtSubText);
txtDescription = (WebView) findViewById(R.id.txtDescription);
btnAdd = (Button) findViewById(R.id.btnAdd);
//btnShare = (Button) findViewById(R.id.btnShare);
sclDetail = (ScrollView) findViewById(R.id.sclDetail);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
// get screen device width and height
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int wPix = dm.widthPixels;
int hPix = wPix / 2 + 50;
// change menu image width and height
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(wPix, hPix);
imgPreview.setLayoutParams(lp);
imageLoader = new ImageLoader(ActivityMenuDetail.this);
dbhelper = new DBHelper(this);
// get menu id that sent from previous page
Intent iGet = getIntent();
Menu_ID = iGet.getLongExtra("menu_id", 0);
// Menu detail API url
MenuDetailAPI = Constant.MenuDetailAPI+"?accesskey="+Constant.AccessKey+"&menu_id="+Menu_ID;
// call asynctask class to request data from server
new getDataTask().execute();
// event listener to handle add button when clicked
btnAdd.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
// show input dialog
addtoCart();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_detail, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.cart:
// refresh action
Intent iMyOrder = new Intent(ActivityMenuDetail.this, ActivityCart.class);
startActivity(iMyOrder);
overridePendingTransition (R.anim.open_next, R.anim.close_next);
return true;
case android.R.id.home:
// app icon in action bar clicked; go home
this.finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// method to show number of order form
void addtoCart(){
// open database first
try{
dbhelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
if(dbhelper.isDataExist(Menu_ID)){
dbhelper.updateData(Menu_ID, 1, (Menu_price));
}else{
dbhelper.addData(Menu_ID, Menu_name, 1, (Menu_price));
}
startActivity(new Intent(ActivityMenuDetail.this,ActivityCart.class));
};
// asynctask class to handle parsing json in background
public class getDataTask extends AsyncTask<Void, Void, Void>{
// show progressbar first
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(8);
// if internet connection and data available show data
// otherwise, show alert text
if((Menu_name != null) && IOConnect == 0){
sclDetail.setVisibility(0);
imageLoader.DisplayImage(Constant.AdminPageURL+Menu_image, imgPreview);
txtText.setText(Menu_name);
txtSubText.setText("Price : " +Menu_price+" "+ActivityMenuList.Currency+"\n"+"Status : "+Menu_serve+"\n"+"Empty Slots : "+Menu_quantity);
txtDescription.loadDataWithBaseURL("", Menu_description, "text/html", "UTF-8", "");
txtDescription.setBackgroundColor(Color.parseColor("#e7e7e7"));
}else{
txtAlert.setVisibility(0);
}
}
}
// method to parse json data from server
public void parseJSONData(){
try {
// request data from menu detail API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(MenuDetailAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into tax and currency variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(i);
JSONObject menu = object.getJSONObject("Menu_detail");
Menu_image = menu.getString("Menu_image");
Menu_name = menu.getString("Menu_name");
Menu_price = Double.valueOf(formatData.format(menu.getDouble("Price")));
Menu_serve = menu.getString("Serve_for");
Menu_description = menu.getString("Description");
Menu_quantity = menu.getInt("Quantity");
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// close database before back to previous page
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
dbhelper.close();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
//imageLoader.clearCache();
super.onDestroy();
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
}
and debhelper class here
public class DBHelper extends SQLiteOpenHelper{
String DB_PATH;
private final static String DB_NAME = "db_order";
public final static int DB_VERSION = 1;
public static SQLiteDatabase db;
private final Context context;
private final String TABLE_NAME = "tbl_order";
private final String ID = "id";
private final String MENU_NAME = "Menu_name";
private final String QUANTITY = "Quantity";
private final String TOTAL_PRICE = "Total_price";
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
DB_PATH = Constant.DBPath;
}
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
SQLiteDatabase db_Read = null;
if(dbExist){
//do nothing - database already exist
}else{
db_Read = this.getReadableDatabase();
db_Read.close();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase(){
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private void copyDataBase() throws IOException{
InputStream myInput = context.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException{
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
#Override
public void close() {
db.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
/** this code is used to get all data from database */
public ArrayList<ArrayList<Object>> getAllData(){
ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
Cursor cursor = null;
try{
cursor = db.query(
TABLE_NAME,
new String[]{ID, MENU_NAME, QUANTITY, TOTAL_PRICE},
null,null, null, null, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()){
do{
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getLong(0));
dataList.add(cursor.getString(1));
dataList.add(cursor.getString(2));
dataList.add(cursor.getString(3));
dataArrays.add(dataList);
}
while (cursor.moveToNext());
}
cursor.close();
}catch (SQLException e){
Log.e("DB Error", e.toString());
e.printStackTrace();
}
return dataArrays;
}
/** this code is used to get all data from database */
public boolean isDataExist(long id){
boolean exist = false;
Cursor cursor = null;
try{
cursor = db.query(
TABLE_NAME,
new String[]{ID},
ID +"="+id,
null, null, null, null);
if(cursor.getCount() > 0){
exist = true;
}
cursor.close();
}catch (SQLException e){
Log.e("DB Error", e.toString());
e.printStackTrace();
}
return exist;
}
/** this code is used to get all data from database */
public boolean isPreviousDataExist(){
boolean exist = false;
Cursor cursor = null;
try{
cursor = db.query(
TABLE_NAME,
new String[]{ID},
null,null, null, null, null);
if(cursor.getCount() > 0){
exist = true;
}
cursor.close();
}catch (SQLException e){
Log.e("DB Error", e.toString());
e.printStackTrace();
}
return exist;
}
public void addData(long id, String menu_name, int quantity, double total_price){
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
values.put(ID, id);
values.put(MENU_NAME, menu_name);
values.put(QUANTITY, quantity);
values.put(TOTAL_PRICE, total_price);
// ask the database object to insert the new data
try{db.insert(TABLE_NAME, null, values);}
catch(Exception e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public void deleteData(long id){
// ask the database manager to delete the row of given id
try {db.delete(TABLE_NAME, ID + "=" + id, null);}
catch (Exception e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public void deleteAllData(){
// ask the database manager to delete the row of given id
try {db.delete(TABLE_NAME, null, null);}
catch (Exception e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public void updateData(long id, int quantity, double total_price){
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
values.put(QUANTITY, quantity);
values.put(TOTAL_PRICE, total_price);
// ask the database object to update the database row of given rowID
try {db.update(TABLE_NAME, values, ID + "=" + id, null);}
catch (Exception e)
{
Log.e("DB Error", e.toString());
e.printStackTrace();
}
}}
The logcat says your dbhelper object is null when preforming close()
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
if (dbhelper != null)
dbhelper.close();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
}
That should fix the problem
From the error trace that you have provided, it seems that "db" instance in DBHelper is null. Therefore in your onBackPressed() when you try to close db by called dbHelper.close(), it's throwing the NullPointerException. Adding a null check will help.
// close database before back to previous page
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
dbhelper.close();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
}
The above function will eventually call the function below:
#Override
public void close() {
db.close();
}
Add a null check for "db"
#Override
public void close() {
if (db != null) {
db.close();
}
}
In a quick glance of your code, it seems that you are opening DB only on action like "add to cart".
void addtoCart(){
// open database first
try{
dbhelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
if(dbhelper.isDataExist(Menu_ID)){
dbhelper.updateData(Menu_ID, 1, (Menu_price));
}else{
dbhelper.addData(Menu_ID, Menu_name, 1, (Menu_price));
}
startActivity(new Intent(ActivityMenuDetail.this,ActivityCart.class));
};
If you try to close the screen without performing such action DB object would not be available.
This is because it may getting null object reference of dbhelper and also it doesn't need to use finish(); as when onBackPressed() called activity finished automatically.
if (dbhelper != null)
dbhelper.close();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
super.onBackPressed();
According to logcat you dbhelper is null, so its giving a NULL POINTER EXCEPTION.
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
dbhelper.close();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
}
In the above method, super.onBackPressed(); is called first before closing the database, which is not a good practice.
Change it to,
#Override
public void onBackPressed() {
if (dbhelper != null)
dbhelper.close();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
super.onBackPressed();
}
Also change,
public void close() {
db.close();
}
to
public void close() {
if(db!=null)
db.close();
}
in Dbhelper.class

Problems in change text of a textview

I have a problem in change a text of a textview in android, i'm starting in android, ok I want do a chat with sockets, I made the socket and connected on server but i can't change the text of the textview, ok this is the code:
public class Cliente extends Activity {
Button conect;
Button env;
EditText ip;
EditText nome;
EditText msg;
String nome_txt;
String ip_txt;
Socket cl;
String texto = "";
TextView log;
boolean a = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_layout);
conect = (Button) findViewById(R.id.conect);
env = (Button) findViewById(R.id.env);
msg = (EditText) findViewById(R.id.msg);
ip = (EditText) findViewById(R.id.ip_tx);
nome = (EditText) findViewById(R.id.nm_tx);
log = (TextView) findViewById(R.id.log);
conect.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
ip_txt = ip.getText().toString();
nome_txt = nome.getText().toString();
setContentView(R.layout.activity_cliente);
Thread th =new Thread(new Ct());
Log.d("Iniciado", "th");
log.setText("asd");
th.start();
}
});
env.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
envMSG(msg.getText().toString());
msg.setText("");
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public void envMSG(String msg) throws IOException {
DataOutputStream outToServer = new DataOutputStream(cl.getOutputStream());
outToServer.writeBytes(msg + '\n');
}
public String serOUT() {
try{
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(cl.getInputStream()));
if (inFromServer.ready()) {
String texto = inFromServer.readLine();
return texto;
} else {
return null;
}
}catch(IOException e){
return null;
}
}
public class Ct extends Thread implements Runnable{
#Override
public void run() {
try {
cl = new Socket(ip_txt, 1111);
envMSG(nome_txt);
do{
String tx = serOUT();
if (tx != null) {
texto += tx + "\n";
log.setText(texto);
envMSG("ola");
}
Log.d("Status",cl.isClosed()+"");
this.sleep(10);
}while (true);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Please tell the error reason, and show examples.
Thanks for Reading.
ass.:Lucas Avelino
First of all, you cant set text inside thread, you have to ovveride runOnUiThread method and try to set text in this method.
public class Ct extends Thread implements Runnable{
#Override
public void run() {
try {
cl = new Socket(ip_txt, 1111);
envMSG(nome_txt);
do{
String tx = serOUT();
if (tx != null) {
runOnUiThread(new Runnable() {
#Override
public void run() {
texto += tx + "\n";
log.setText(texto);
envMSG("ola");
}
});
}
Log.d("Status",cl.isClosed()+"");
this.sleep(10);
}while (true);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

How to save text entered in EditText after orientation changed?

I have two activities:
1.Main Activity which contains listview;
2.Second Activity which add item to listview in Main Activity.
For Second Activity I created layout-land layout for landscape.
After Second Activity is opens in portrait, I change it to landscape mode - Second Activity close and app return to Main Activity.
Questions:
1.How save entered to EditText fields values after orientation is changed?
2.And how to apply layout-land to Second Activity when change screen orientation to landscape?
UPD
Second activity code:
public class AddItem extends MainScreen implements OnClickListener{
final String LOG_TAG = "myLogs";
EditText comment_enter, link_enter, password_enter, login_enter, title_enter, date_enter;
Button add_item_button, add_more_button, clear_close_button;
CheckBox showPass;
DBHelper db;
DataBase DB;
SimpleCursorAdapter passListViewAdapter;
SimpleDateFormat sdf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_item);
Log.d(LOG_TAG, "before edit : ");
comment_enter = (EditText) findViewById(R.id.comment_enter);
link_enter = (EditText) findViewById(R.id.link_enter);
password_enter = (EditText) findViewById(R.id.password_enter);
login_enter = (EditText) findViewById(R.id.login_enter);
title_enter = (EditText) findViewById(R.id.title_enter);
date_enter = (EditText) findViewById(R.id.date_enter);
showPass = (CheckBox) findViewById(R.id.showPass);
showPass.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Log.d(LOG_TAG, "is checked : " + isChecked);
if (isChecked) {
password_enter.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
}
else {
password_enter.setInputType(129);
}
}
});
add_item_button = (Button) findViewById(R.id.add_item_button);
add_item_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d(LOG_TAG, "add_item_button : ");
String title_str = title_enter.getText().toString();
String login_str = login_enter.getText().toString();
String pass_str = password_enter.getText().toString();
String link_str = link_enter.getText().toString();
String comm_str = comment_enter.getText().toString();
String date_str = date_enter.getText().toString();
byte[] login_byted = null;
try {
login_byted = login_str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String login_crypted = Base64.encodeToString(login_byted, Base64.DEFAULT);
Log.d(LOG_TAG, "Crypted login" + login_crypted);
byte[] pass_byted = null;
try {
pass_byted = pass_str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String pass_crypted = Base64.encodeToString(pass_byted, Base64.DEFAULT);
Log.d(LOG_TAG, "Crypted login" + pass_crypted);
DataBase DB = new DataBase(AddItem.this);
DB.open();
DB.insertPass(title_str, login_crypted, pass_crypted, link_str, comm_str, date_str);
DB.close();
Log.d(LOG_TAG, "after inserting into DB : ");
finish();
}
});
add_more_button = (Button) findViewById(R.id.add_more_button);
add_more_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d(LOG_TAG, "add_more_button : ");
String title_str = title_enter.getText().toString();
String login_str = login_enter.getText().toString();
String pass_str = password_enter.getText().toString();
String link_str = link_enter.getText().toString();
String comm_str = comment_enter.getText().toString();
String date_str = date_enter.getText().toString();
byte[] login_byted = null;
try {
login_byted = login_str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String login_crypted = Base64.encodeToString(login_byted, Base64.DEFAULT);
Log.d(LOG_TAG, "Crypted login" + login_crypted);
byte[] pass_byted = null;
try {
pass_byted = pass_str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String pass_crypted = Base64.encodeToString(pass_byted, Base64.DEFAULT);
Log.d(LOG_TAG, "Crypted login" + pass_crypted);
DataBase DB = new DataBase(AddItem.this);
DB.open();
DB.insertPass(title_str, login_crypted, pass_crypted, link_str, comm_str, date_str);
DB.close();
Log.d(LOG_TAG, "after inserting into DB : ");
fieldClear();
String link_enter_str = link_enter.getText().toString();
if(link_enter_str.equals("")){
link_enter.setText("http://www.");
}
}
});
clear_close_button = (Button) findViewById(R.id.clear_close_button);
clear_close_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d(LOG_TAG, "clear/close click button : ");
boolean checkRes = emptyAllCheck();
Log.d(LOG_TAG, "result : " + checkRes);
if(checkRes == true){
finish();
}
fieldClear();
}
});
if(savedInstanceState != null){
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Log.d(LOG_TAG, "title : " + savedInstanceState.getString("title"));
title_enter.setText(savedInstanceState.getString("title"));
login_enter.setText(savedInstanceState.getString("login"));
password_enter.setText(savedInstanceState.getString("pass"));
link_enter.setText(savedInstanceState.getString("link"));
comment_enter.setText(savedInstanceState.getString("comm"));
date_enter.setText(savedInstanceState.getString("date"));
add_item_button = (Button) findViewById(R.id.add_item_button);
add_more_button = (Button) findViewById(R.id.add_more_button);
}
else {
Log.d(LOG_TAG, "before getting date : ");
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String date = sdf.format(new Date(System.currentTimeMillis()));
date_enter.setText(date);
}
}
#Override
protected void onPause() {
super.onPause();
finish();
Log.d(LOG_TAG, "onPause : ");
}
#Override
protected void onResume(){
super.onResume();
}
protected void onSaveInstanceState(Bundle saveInstance) {
super.onSaveInstanceState(saveInstance);
String title_str = title_enter.getText().toString();
String login_str = login_enter.getText().toString();
String pass_str = password_enter.getText().toString();
String link_str = link_enter.getText().toString();
String comm_str = comment_enter.getText().toString();
String date_str = date_enter.getText().toString();
saveInstance.putString("title", title_str);
saveInstance.putString("login", login_str);
saveInstance.putString("pass", pass_str);
saveInstance.putString("link", link_str);
saveInstance.putString("comm", comm_str);
saveInstance.putString("date", date_str);
Log.d(LOG_TAG, "onSaveInstanceState +" + title_str + login_str + pass_str + link_str + comm_str + date_str);
}
public void fieldClear(){
comment_enter.setText("");
link_enter.setText("http://www.");
password_enter.setText("");
login_enter.setText("");
title_enter.setText("");
}
public boolean emptyAllCheck(){
String title_str = title_enter.getText().toString();
String login_str = login_enter.getText().toString();
String pass_str = password_enter.getText().toString();
String link_str = link_enter.getText().toString();
String comm_str = comment_enter.getText().toString();
if (title_str.equals("") && login_str.equals("") && pass_str.equals("") && link_str.equals("http://www.") && comm_str.equals("")) {
return true;
}
return false;
}
}
i advise you to read a bit more about Android Activity life cycle it will help you.
However on configuration Change android destroy you are activity and recreate and you can use the callback method OnsavedInstanceState() to save you instance (it will be call automatically by the system on configuration change)
example
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);{
String savedText = myEditText.getText().toString();
savedInstanceState.putString("Key", savedText);
}
Now when the app is recreated on OnCreate method retrieve your saved text as follow :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null){
myEditText.setText(savedInstanceState.getString("Key");
//the rest of the code}
Voila and I hope that is that you meant.
use this one:
android:configChanges="orientation|screenSize"
add this code in your manifest file. No need to save the edit text variable.

When I press backspace did the AutoCompleteTextView show the suggestion list

My code is following ...
public class NameListActivity extends Activity implements TextWatcher {
private Button add = null;
private AutoCompleteTextView editAuto = null;
private Button chfrlist = null;
private ImageView im = null;
String access_token = new String();
private ImageView infobtn = null;
private PopupWindow popupWindow;
private View view;
private ProgressDialog pd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_name_list);
access_token = MainService.readToken();
add = (Button) findViewById(R.id.add_button);
editAuto = (AutoCompleteTextView) findViewById(R.id.editAuto);
chfrlist = (Button) findViewById(R.id.chfrlistbutton);
im = (ImageView) findViewById(R.id.helpact);
im.setOnClickListener(new ImageListener());
infobtn = (ImageView) findViewById(R.id.informbtn);
initPopupWindow();
infobtn.setOnClickListener(new infobtnListener());
editAuto.addTextChangedListener(this);
add.setOnClickListener(new addListener());
chfrlist.setOnClickListener(new ChfrListListener());
}
public class addListener implements OnClickListener {
public void onClick(View v) {
addTask task = new addTask();
task.execute();
editAuto.setText("");
}
}
public void afterTextChanged(Editable arg0) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
onTextChangedTask task = new onTextChangedTask();
task.execute();
}
public class onTextChangedTask extends AsyncTask<Void, Void, Void> {
ArrayAdapter<String> adapter = null;
String[] userName = null;
String q = null;
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = null;
ArrayList<String> userNameArrayList = new ArrayList<String>();
Weibo weibo = new Weibo();
#Override
protected void onPreExecute() {
weibo.setToken(access_token);
q = editAuto.getText().toString();
System.out.println("start onTextChanged");
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
if (q.length() != 0) {
System.out.println("q is " + q);
String s1 = "https://api.weibo.com/search/suggestions/users.json";
try {
jsonArray = Weibo.client.get(s1,
new PostParameter[] { new PostParameter("q", q) })
.asJSONArray();
} catch (Throwable e) {
System.out.println("这里有个神马异常呢 。。。" + e);
}
System.out.println("return length is " + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
try {
jsonObject = jsonArray.getJSONObject(i);
String sname = jsonObject.getString("screen_name");
userNameArrayList.add(sname);
} catch (JSONException e) {
e.printStackTrace();
}
}
userName = (String[]) userNameArrayList
.toArray(new String[userNameArrayList.size()]);
adapter = new ArrayAdapter<String>(NameListActivity.this,
android.R.layout.simple_dropdown_item_1line, userName);
}
return null;
}
#Override
protected void onPostExecute(Void v) {
System.out.println("post");
editAuto.setAdapter(adapter);
}
}
void showToast(String s) {
Toast toast = Toast.makeText(getApplicationContext(), s,
Toast.LENGTH_LONG);
toast.show();
}
public class addTask extends AsyncTask<Void, Void, Void> {
String s = null;
boolean flag = false;
User user = null;
Weibo weibo = new Weibo();
String screen_name = null;
protected void onPreExecute() {
Toast tt = Toast.makeText(getApplicationContext(), "正在将用户添加到备份名单",
Toast.LENGTH_LONG);
tt.setGravity(Gravity.CENTER, 0, 0);
tt.show();
weibo.setToken(access_token);
screen_name = editAuto.getText().toString();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
if (screen_name.length() != 0) {
Users um = new Users();
try {
user = new User(Weibo.client.get(
"https://api.weibo.com/users/show.json",
new PostParameter[] { new PostParameter(
"screen_name", screen_name) })
.asJSONObject());
} catch (Throwable e) {
e.printStackTrace();
flag = true;
s = new String("您输入的这个用户好像不存在唉");
}
if (user != null) {
ContentValues values = new ContentValues();
values.put("uid", user.getId());
values.put("user_name", user.getName());
SQLiteDatabase db = null;
try {
db = MainService.getDatabase();
} catch (Exception e) {
System.out.println("db error");
finish();
}
Cursor result = db.query("users", new String[] { "uid",
"user_name" }, "uid=?",
new String[] { user.getId() }, null, null, null);
if (result.getCount() == 0)
db.insert("users", null, values);
} else {
flag = true;
s = new String("网络存在问题,检查一下吧");
}
} else {
flag = true;
s = new String("框里输入点东西才能添加啊");
}
return null;
}
#Override
protected void onPostExecute(Void v) {
if (flag == true) {
System.out.println("要打印的是" + s);
showToast(s);
}
}
}
public class infobtnListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("点击了图片");
ColorDrawable cd = new ColorDrawable(-0000);
popupWindow.setBackgroundDrawable(cd);
// popupWindow.showAsDropDown(v);
popupWindow.showAtLocation(findViewById(R.id.informbtn),
Gravity.LEFT | Gravity.BOTTOM, 0, 100);
}
}
public class ImageListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
// Intent t = new Intent(NameListActivity.this,
// GridLayoutActivity.class);
// startActivity(t);
finish();
}
}
public class ChfrListListener implements OnClickListener {
public void onClick(View v) {
if ((haveInternet() == true)
&& (GridLayoutActivity.hasAccessToken() == true)) {
// TODO Auto-generated method stub
pd = ProgressDialog.show(NameListActivity.this, "",
"正在从服务器上获取数据,可能需要较长时间,请耐心等待 ...");
/* 开启一个新线程,在新线程里执行耗时的方法 */
new Thread(new Runnable() {
public void run() {
Intent t = new Intent(NameListActivity.this,
ChooseFromListActivity.class);
startActivity(t);
finish();
handler.sendEmptyMessage(0);// 执行耗时的方法之后发送消给handler
}
}).start();
} else {
Intent t = new Intent(NameListActivity.this,
WebViewActivity.class);
startActivity(t);
finish();
}
}
}
private void initPopupWindow() {
view = getLayoutInflater().inflate(R.layout.namewindow, null);
popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
// 这里设置显示PopuWindow之后在外面点击是否有效。如果为false的话,那么点击PopuWindow外面并不会关闭PopuWindow。
popupWindow.setOutsideTouchable(true);// 不能在没有焦点的时候使用
}
private boolean haveInternet() {
NetworkInfo info = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
// here is the roaming option you can change it if you want to
// disable internet while roaming, just return false
return true;
}
return true;
}
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {// handler接收到消息后就会执行此方法
pd.dismiss();// 关闭ProgressDialog
}
};
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_name_list, menu);
return true;
}
}
My question is : when I input words in the EditText, nothing happened. But when I press backspace did the AutoCompleteTextView show the suggestion list ... the problem is in the editAuto.setAdapter(adapter);
What is wrong?
make the following changes in your code
1) Instead of
private AutoCompleteTextView editAuto = null; JUST WRITE private AutoCompleteTextView editAuto;
2) Add this line to onCrate()
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, <your array name here>);
and remove this line from onTextChangedTask()
ArrayList<String> userNameArrayList = new ArrayList<String>();
3) Add this line to onCrate()
editAuto.setAdapter(adapter);
I know this is way late but for those who face similar problems here is the solution to show the autoCompleteTextView's drop down whenever you want i.e on button click or onTextChanged. After you set the ArrayAdapter for the autoCompleteTextView just put the following line.
autoCompleteTextView.showDropDown();

problem accessing run() in android

Hi i have a problem accessing run() method in my program. The rum method is not getting focus at all. The Log message that is present outside the loop is getting displayed and i am getting a blank screen with preset background.Here's the code...
public class MusicListActivity extends Activity {
List<HashMap<String, String>> songNodeDet = new ArrayList<HashMap<String,String>>();
HashMap<?,?>[] songNodeWeb;
XMLRPCClient client;
String logInSess;
ArrayList<String> paths=new ArrayList<String>();
public ListAdapter adapter ;
Object[] websongListObject;
List<SongsList> SongsList=new ArrayList<SongsList>();
Runnable r;
ProgressDialog p;
ListView lv;
#Override
public void onCreate(Bundle si){
super.onCreate(si);
setContentView(R.layout.openadiuofile);
lv=(ListView)findViewById(R.id.list1);
r=new Runnable(){
public void run(){
try{
getSongs();
list();
Log.d("handler","handler");
removeDialog(0);
p.dismiss();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XMLRPCException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Log.e("***","process over");
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
public void webObjectList(Object[] songListObj) throws XMLRPCException{
songNodeWeb = new HashMap<?,?>[songListObj.length];
for(int i=0;i<songListObj.length;i++){
songNodeWeb[i]=(HashMap<?,?>)songListObj[i];
String nodeid=(String) songNodeWeb[i].get("nid");
Log.e("Song",i+"completed");
HashMap<String,String> nData=new HashMap<String,String>();
nData.put("nid",nodeid);
Object nodeget=client.call("node.get",nodeid);
HashMap<?,?> songNode=(HashMap<?,?>)nodeget;
String title=(String) songNode.get("title");
String album=(String) songNode.get("album");
String artist=(String) songNode.get("artist");
nData.put("title", title);
nData.put("album", album);
nData.put("artist", artist);
Object[] songObject=(Object[])songNode.get("title_format");
HashMap<?,?>[] songDetails=new HashMap<?,?>[songObject.length];
songDetails[0]=(HashMap<?, ?>)songObject[0];
String path=(String) songDetails[0].get("filepath");
if(path.contains(" ")){
path=path.replace(" ", "%20");
}
String songPath="http://www.gorinka.com/"+path;
paths.add(songPath);
nData.put("path", songPath);
Log.e("my path",path);
SongsList songsList=new SongsList(title, album, artist,songPath,songPath);
SongsList.add(i,songsList);
songNodeDet.add(i,nData);
}
Log.e("paths values",paths.toString());
handler.sendEmptyMessage(0);
}
public void list()
{ Log.d("#####","#####");
LayoutInflater inflater=getLayoutInflater();
String[] from={};
int[] n={};
adapter=new SongsAdapter(getApplicationContext(),songNodeDet,R.layout.row,from,n,inflater);
lv.setAdapter(adapter);
}
public void getSongs() throws MalformedURLException, XMLRPCException
{
String ur="http://www.gorinka.com/";
URL u=new URL(ur);
client = new XMLRPCClient(u);
websongListObject =(Object[]) client.call("nodetype.get","titles");
webObjectList(websongListObject);
Log.d("webObjectList","webObjectList");
runOnUiThread(r);
}
private Handler handler = new Handler() {
public void handleMessage(Message msg){
Log.d("handler","handler");
removeDialog(0);
p.dismiss();
}
};
}
I m trying to access the strings through simple adapter... Here's the code for adapter...
public class SongsAdapter extends SimpleAdapter{
static List<HashMap<String,String>> songsList;
Context context;
LayoutInflater inflater;
public SongsAdapter(Context context,List<HashMap<String,String>> imgListWeb,int layout,String[] from,int[] to,LayoutInflater inflater) {
super(context,songsList,layout,from,to);
this.songsList=songsList;
this.context=context;
this.inflater=inflater;
// TODO Auto-generated constructor stub
}
#Override
public View getView(int postition,View convertView,ViewGroup parent)throws java.lang.OutOfMemoryError{
try {
View v = ((LayoutInflater) inflater).inflate(R.layout.row,null);
ImageView images=(ImageView)v.findViewById(R.id.image);
TextView tvTitle=(TextView)v.findViewById(R.id.text1);
TextView tvAlbum=(TextView)v.findViewById(R.id.text2);
TextView tvArtist=(TextView)v.findViewById(R.id.text3);
HashMap<String,String> songsHash=songsList.get(postition);
String path=songsHash.get("path");
String title=songsHash.get("title");
String album=songsHash.get("album");
String artist=songsHash.get("artist");
String imgPath=path;
final ImageView imageView = (ImageView) v.findViewById(R.id.image);
AsyncImageLoaderv asyncImageLoader=new AsyncImageLoaderv();
Bitmap cachedImage = asyncImageLoader.loadDrawable(imgPath, new AsyncImageLoaderv.ImageCallback() {
public void imageLoaded(Bitmap imageDrawable, String imageUrl) {
imageView.setImageBitmap(imageDrawable);
}
});
imageView.setImageBitmap(cachedImage);
tvTitle.setText(title);
tvAlbum.setText(album);
tvArtist.setText(artist);
return v;
}
catch(Exception e){
Log.e("error",e.toString());
}
return null;
}
public static Bitmap loadImageFromUrl(String url) {
InputStream inputStream;Bitmap b;
try {
inputStream = (InputStream) new URL(url).getContent();
BitmapFactory.Options bpo= new BitmapFactory.Options();
bpo.inSampleSize=2;
b=BitmapFactory.decodeStream(inputStream, null,bpo );
return b;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Plz help me determinre the problem and solution for my problem... Need it badly...
First of all, I would recommend you using AsyncTask.
The mistake here is that you are creating a Runnable but not passing it to a new Thread()
You are missing something like this:
Thread heavyLoader = new Thread(r);
heavyLoader.start();

Categories

Resources