i got my app working so it returns the information from a json api.
now i realize that i have to put everything in a asynch task so it doesn't crash as much
and a progress dialog is easier, only i really don't know how to do this so im wondering if somebody knows a really good tutorial or wants to edit my code a bit to get my started
package net.thinkbin;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class culture extends ListActivity {
private static final String TITLE = "Title";
private static final String AUTHOR = "Author";
private static final String VIEWS = "Views";
private static final String RATES = "Rates";
private static final String CONTENT = "Content";
final Context context = this;
JSONArray ideas = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder2);
Button view = (Button) findViewById(R.id.button1);
view.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("net.thinkbin.TUTORIAL1"));
overridePendingTransition(0, 0);
finish();
}
});
Button share = (Button) findViewById(R.id.button2);
share.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("net.thinkbin.SHARE"));
overridePendingTransition(0, 0);
finish();
}
});
Button menu = (Button) findViewById(R.id.buttonhome);
menu.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Loading...");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.hourglass);
dialog.show();
Thread th = new Thread(new Runnable() {
public void run() {
startActivity(new Intent("net.thinkbin.MENU"));
overridePendingTransition(0, 0);
dialog.dismiss();
finish();
}
});
th.start();
}
});
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
this, R.array.spinnerorder,
android.R.layout.simple_spinner_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner s = (Spinner) findViewById(R.id.cultureorder);
s.setAdapter(adapter2);
s.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapter2, View view,
int position, long id) {
if (position == 1) {
startActivity(new Intent("net.thinkbin.CULTURE2"));
overridePendingTransition(0, 0);
finish();
}
if (position == 2) {
startActivity(new Intent("net.thinkbin.CULTURE3"));
overridePendingTransition(0, 0);
finish();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions
.getJSONfromURL("http://www.thinkbin.net/include/api/index.php? cat=Culture&type=Newest&i=10");
try {
ideas = json.getJSONArray("Ideas");
for (int i = 0; i < ideas.length(); i++) {
JSONObject c = ideas.getJSONObject(i);
String title = c.getString(TITLE);
String author = c.getString(AUTHOR);
String views = c.getString(VIEWS);
String rates = c.getString(RATES);
String content = c.getString(CONTENT);
HashMap<String, String> map = new HashMap<String, String> ();
map.put(TITLE, "Title: " + title);
map.put(AUTHOR, "Author: " + author);
map.put(VIEWS, "Views: " + views);
map.put(RATES, "Rates: " + rates);
map.put(CONTENT, content);
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.main2,
new String[] { TITLE, AUTHOR, VIEWS, RATES, CONTENT },
new int[] { R.id.item_title, R.id.item_subtitle, R.id.item3,
R.id.item4, R.id.item5 });
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String Title2 = ((TextView) view.findViewById(R.id.item_title))
.getText().toString();
String Author2 = ((TextView) view
.findViewById(R.id.item_subtitle)).getText().toString();
String Content2 = ((TextView) view.findViewById(R.id.item5))
.getText().toString();
Intent in = new Intent(getApplicationContext(), idea.class);
overridePendingTransition(0, 0);
in.putExtra(TITLE, Title2);
in.putExtra(AUTHOR, Author2);
in.putExtra(CONTENT, Content2);
startActivity(in);
}
});
}
}
There is good class AsyncTask to do something Asyncronius in Android.
Example:
private class DownloadFilesTask extends AsyncTask
{
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
} }
http://developer.android.com/reference/android/os/AsyncTask.html
Related
I am new to Android development, I am working on a App and I want to convert my below mentioned code to AnsyncTask. Because it is showing me Run-time error that I am doing too much work on UI thread. Please help me to convert it to AnsyncTask.
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class PlayActivity extends AppCompatActivity {
GridView gridview;
TextView textView;
TextView result;
TextView remainingChance;
Button giveup;
Button goback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
textView = (TextView) findViewById(R.id.blanks);
result = (TextView) findViewById(R.id.result);
remainingChance = (TextView) findViewById(R.id.remainingChance);
giveup = (Button) findViewById(R.id.giveup);
goback = (Button) findViewById(R.id.goback);
goback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent goBack = new Intent(PlayActivity.this, MainActivity.class);
startActivity(goBack);
}
});
String dash = "";
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String easyArray[] = bundle.getStringArray("easy");
final String randomStr = easyArray[new Random().nextInt(easyArray.length)]; // Getting a random string from Array
giveup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(randomStr); // By clicking on Give up button, it displays the actual word & a message Go Back and try again
remainingChance.setText("Go Back and try again");
}
});
final Integer strLength = randomStr.length();
// Creating string with question mark with 2nd and 5th character only
for(int i=1; i<=strLength; i++){
if(i == 2){
dash = dash+Character.toString(randomStr.charAt(1));
} else if (i == 5){
dash = dash+ Character.toString(randomStr.charAt(4));
} else {
dash = dash + "?";
}
}
final String displayVal = dash;
textView.setText(displayVal); // Displaying string with question mark with 2nd and 5th character only
gridview = (GridView) findViewById(R.id.gridview);
final String[] mAlphabets = new String[]{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
final ArrayList<String> array_list = new ArrayList<String>(Arrays.asList(mAlphabets));
final ArrayAdapter arrayAdapter = new ArrayAdapter (getApplicationContext(),android.R.layout.simple_list_item_1,array_list);
gridview.setNumColumns(8);
gridview.setBackgroundColor(Color.BLUE);
gridview.setGravity(Gravity.CENTER);
gridview.setAdapter(arrayAdapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
String finalDisplayVal = displayVal;
int count = 0;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final ProgressDialog mProgressDialog = new ProgressDialog(PlayActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading...");
// Set progressdialog message
mProgressDialog.setMessage("Checkinggg...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
long delayInMillis = 1000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
mProgressDialog.dismiss();
}
}, delayInMillis);
String itemValue = (String) gridview.getItemAtPosition(position);
array_list.remove(position); // Removing character from 26 alphabets which is clicked by user
arrayAdapter.notifyDataSetChanged(); // Reset gridview
if(randomStr.contains(itemValue)){ // If selected alphabets exists in string
for(int k=0; k<strLength; k++){
if(Character.toString(randomStr.charAt(k)).equalsIgnoreCase(itemValue)){
int charPos = randomStr.indexOf(itemValue);
while(charPos >= 0){
finalDisplayVal = replaceCharAt(finalDisplayVal, charPos, itemValue);
textView.setText(finalDisplayVal);
charPos = randomStr.indexOf(itemValue, charPos + 1);
}
}
}
checkWinCount(); // Checking if User Wins
} else {
count++;
int remVal = 4-count;
remainingChance.setText("Not Exist, You have " + remVal + " chance(s) left.");
}
checkLoseCount(); // Checking if User Lose
}
public String replaceCharAt(String s, int pos, String c) {
return s.substring(0, pos) + c + s.substring(pos + 1);
}
public void checkLoseCount() {
if(count > 3) {
Toast.makeText(PlayActivity.this, "You Loose, Value is: "+randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity.this, MainActivity.class);
startActivity(goBack);
}
}
public void checkWinCount(){
if(randomStr.equalsIgnoreCase(finalDisplayVal)){
Toast.makeText(PlayActivity.this, "Hurray!!! You WIN... It's "+randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity.this, MainActivity.class);
startActivity(goBack);
}
}
});
}
}
AsyncTask Code;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.AsyncTask;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class PlayActivity1 extends AppCompatActivity {
GridView gridview;
TextView textView;
TextView result;
TextView remainingChance;
Button giveup;
Button goback;
int count = 0;
String randomStr;
String finalDisplayVal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
textView = (TextView) findViewById(R.id.blanks);
result = (TextView) findViewById(R.id.result);
remainingChance = (TextView) findViewById(R.id.remainingChance);
giveup = (Button) findViewById(R.id.giveup);
goback = (Button) findViewById(R.id.goback);
goback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent goBack = new Intent(PlayActivity1.this, MainActivity.class);
startActivity(goBack);
}
});
String dash = "";
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String easyArray[] = bundle.getStringArray("easy");
final String randomStr = easyArray[new Random().nextInt(easyArray.length)]; // Getting a random string from Array
giveup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(randomStr); // By clicking on Give up button, it displays the actual word & a message Go Back and try again
remainingChance.setText("Go Back and try again");
}
});
final Integer strLength = randomStr.length();
// Creating string with question mark with 2nd and 5th character only
for (int i = 1; i <= strLength; i++) {
if (i == 2) {
dash = dash + Character.toString(randomStr.charAt(1));
} else if (i == 5) {
dash = dash + Character.toString(randomStr.charAt(4));
} else {
dash = dash + "?";
}
}
final String displayVal = dash;
textView.setText(displayVal); // Displaying string with question mark with 2nd and 5th character only
gridview = (GridView) findViewById(R.id.gridview);
final String[] mAlphabets = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
final ArrayList<String> array_list = new ArrayList<String>(Arrays.asList(mAlphabets));
final ArrayAdapter arrayAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, array_list);
gridview.setNumColumns(8);
gridview.setBackgroundColor(Color.BLUE);
gridview.setGravity(Gravity.CENTER);
gridview.setAdapter(arrayAdapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AsyncTaskRunner runner = new AsyncTaskRunner();
String finalDisplayVal = displayVal;
runner.execute(finalDisplayVal);
String itemValue = (String) gridview.getItemAtPosition(position);
array_list.remove(position); // Removing character from 26 alphabets which is clicked by user
arrayAdapter.notifyDataSetChanged(); // Reset gridview
if (randomStr.contains(itemValue)) { // If selected alphabets exists in string
for (int k = 0; k < strLength; k++) {
if (Character.toString(randomStr.charAt(k)).equalsIgnoreCase(itemValue)) {
int charPos = randomStr.indexOf(itemValue);
while (charPos >= 0) {
finalDisplayVal = replaceCharAt(finalDisplayVal, charPos, itemValue);
textView.setText(finalDisplayVal);
charPos = randomStr.indexOf(itemValue, charPos + 1);
}
}
}
checkWinCount(); // Checking if User Wins
} else {
count++;
int remVal = 4 - count;
remainingChance.setText("Not Exist, You have " + remVal + " chance(s) left.");
}
checkLoseCount(); // Checking if User Lose
}
});
}
public String replaceCharAt(String s, int pos, String c) {
return s.substring(0, pos) + c + s.substring(pos + 1);
}
public void checkLoseCount() {
if (count > 3) {
Toast.makeText(PlayActivity1.this, "You Loose, Value is: " + randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity1.this, MainActivity.class);
startActivity(goBack);
}
}
public void checkWinCount() {
if (randomStr.equalsIgnoreCase(finalDisplayVal)) {
Toast.makeText(PlayActivity1.this, "Hurray!!! You WIN... It's " + randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity1.this, MainActivity.class);
startActivity(goBack);
}
}
private class AsyncTaskRunner extends AsyncTask<String, String, ProgressDialog> {
#Override
protected ProgressDialog doInBackground(String... params) {
final ProgressDialog mProgressDialog = new ProgressDialog(PlayActivity1.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading...");
// Set progressdialog message
mProgressDialog.setMessage("Checkinggg...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
try {
long delayInMillis = 1000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
mProgressDialog.dismiss();
}
}, delayInMillis);
}catch (Exception e){
e.printStackTrace();
}
return mProgressDialog;
}
}
}
Hi i have this android project where after searching for an Author in the app and the results is clicked i get an empty view instead of the Author displaying his or her quotes
This is the code am using...Thanks
package com.dennisboga.successquotes;
import java.util.ArrayList;
import java.util.HashMap;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import android.widget.AdapterView.OnItemClickListener;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
public class AuthorsActivity extends Activity {
ListView list;
LazyAuthorsAdapter adapter;
LazyAuthorsAdapter adapterSort;
DAO db;
Cursor cu;
static final String KEY_ID = "_auid";
static final String KEY_NAME = "au_name";
static final String KEY_PICTURE = "au_picture";
static final String KEY_PICTURE_SDCARD = "au_picture_sdcard";
static final String KEY_WEB_ID = "au_web_id";
static final String KEY_COUNT = "count";
static final String KEY_QUOTES_NUM = "quotes_num";
ImageButton search;
EditText inputSearch;
int textlength = 0;
ArrayList<HashMap<String, String>> authorsList;
ArrayList<HashMap<String, String>> authorsListSort = new ArrayList<HashMap<String, String>>();;
HashMap<String, String> map;
// ============================================================================= =
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new DAO(this);
db.open();
//addAuthors();
//addQuotes();
Cursor c = db.getAllAuthors();
if (c.getCount() != 0) {
setContentView(R.layout.activity_authors);
authorsList = new ArrayList<HashMap<String, String>>();
do {
map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, c.getString(c.getColumnIndex(KEY_ID)));
map.put(KEY_NAME, c.getString(c.getColumnIndex(KEY_NAME)));
map.put(KEY_PICTURE, c.getString(c.getColumnIndex(KEY_PICTURE)));
map.put(KEY_PICTURE_SDCARD, String.valueOf(c.getInt(c
.getColumnIndex(KEY_PICTURE_SDCARD))));
map.put(KEY_WEB_ID,
String.valueOf(c.getInt(c.getColumnIndex(KEY_WEB_ID))));
map.put(KEY_QUOTES_NUM,
c.getString(c.getColumnIndex(KEY_COUNT)));
// adding HashList to ArrayList
authorsList.add(map);
} while (c.moveToNext());
list = (ListView) findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter = new LazyAuthorsAdapter(this, authorsList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (authorsListSort.size() != 0) {
map = authorsListSort.get(position);
} else {
map = authorsList.get(position);
}
Intent intent = new Intent(AuthorsActivity.this,
QuotesActivity.class);
intent.putExtra("AuthorId", map.get(KEY_WEB_ID));
intent.putExtra("quotesType", 3);
startActivity(intent);
}
});
search = (ImageButton) findViewById(R.id.search);
inputSearch = (EditText) findViewById(R.id.inputSearch);
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (inputSearch.getVisibility() == View.GONE) {
inputSearch.setVisibility(View.VISIBLE);
} else {
inputSearch.setText("");
inputSearch.setVisibility(View.GONE);
}
}
});
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
authorsListSort.clear();
for (int i = 0; i < authorsList.size(); i++) {
map = authorsList.get(i);
String auID = map.get(KEY_ID);
String auName = map.get(KEY_NAME);
String auPicture = map.get(KEY_PICTURE);
String auPictureSDCard = map.get(KEY_PICTURE_SDCARD);
String auQuotesNum = map.get(KEY_QUOTES_NUM);
if (auName.toLowerCase().startsWith(
s.toString().toLowerCase())
|| auName.toLowerCase().contains(
" " + s.toString().toLowerCase())) {
map = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
map.put(KEY_ID, auID);
map.put(KEY_NAME, auName);
map.put(KEY_PICTURE, auPicture);
map.put(KEY_PICTURE_SDCARD, auPictureSDCard);
map.put(KEY_QUOTES_NUM, auQuotesNum);
// adding HashList to ArrayList
authorsListSort.add(map);
}
}
// }
adapterSort = new LazyAuthorsAdapter(AuthorsActivity.this,
authorsListSort);
list.setAdapter(adapterSort);
}
});
} else {
}
AdView ad = (AdView) findViewById(R.id.adView);
ad.loadAd(new AdRequest.Builder().build());
}
// ============================================================================= =
#Override
protected void onResume() {
db.open();
super.onResume();
}
// ============================================================================= =
#Override
protected void onRestart() {
// TODO Auto-generated method stub
Intent intent = getIntent();
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(intent);
super.onRestart();
}
// ============================================================================= =
#Override
protected void onPause() {
db.closeDatabase();
super.onPause();
}
// private void addAuthors() {
// cu = db.getAuthors2();
//
// if (cu.getCount() != 0) {
//
// do {
// db.addAuthors2(cu.getString(cu.getColumnIndex("au_name")),
// cu.getInt(cu.getColumnIndex("_auid")));
//
// } while (cu.moveToNext());
// }
// }
//
// ============================================================================= =
// private void addQuotes() {
// cu = db.getQuotes2();
//
// if (cu.getCount() != 0) {
//
// do {
// db.addQuotes2(cu.getString(cu.getColumnIndex("qu_text")),
// cu.getInt(cu.getColumnIndex("qu_author")),
// cu.getInt(cu.getColumnIndex("_quid")));
//
// } while (cu.moveToNext());
// }
// }
}
quotesactivity
package com.dennisboga.successquotes;
import java.util.ArrayList;
import java.util.HashMap;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import android.widget.AdapterView.OnItemClickListener;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
public class QuotesActivity extends Activity {
ListView list;
LazyQuotesAdapter adapter;
AlertDialog PageDialog;
DAO db;
Cursor c;
static final String KEY_ID = "_quid";
static final String KEY_TEXT = "qu_text";
static final String KEY_AUTHOR = "au_name";
static final String KEY_PICTURE = "au_picture";
static final String KEY_PICTURE_SDCARD = "au_picture_sdcard";
static final String KEY_WEB_ID = "au_web_id";
static final String KEY_FAVORITE = "qu_favorite";
ArrayList<HashMap<String, String>> quotesList;
HashMap<String, String> map;
ArrayList<HashMap<String, String>> pages;
Integer quType;
ImageButton page;
int itemSelected;
// ==============================================================================
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new DAO(this);
db.open();
setContentView(R.layout.activity_quotes);
AdView ad = (AdView) findViewById(R.id.adView);
ad.loadAd(new AdRequest.Builder().build());
quType = getIntent().getIntExtra("quotesType", 0);
page = (ImageButton) findViewById(R.id.pager);
if (quType != 0) {
switch (quType) {
case 1:
if (getIntent().getStringExtra("startFrom") == null) {
c = db.getQuotes("0");
} else {
c = db.getQuotes(getIntent().getStringExtra("startFrom"));
}
break;
case 2:
c = db.getFavoriteQuotes();
page.setVisibility(View.GONE);
break;
case 3:
c = db.getAuthorQuotes(getIntent().getStringExtra("AuthorId"));
page.setVisibility(View.GONE);
break;
}
}
if (c.getCount() != 0) {
if (getIntent().getStringExtra("startLabel") != null) {
page = (ImageButton) findViewById(R.id.pager);
}
quotesList = new ArrayList<HashMap<String, String>>();
list = (ListView) findViewById(R.id.list);
do {
map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, c.getString(c.getColumnIndex(KEY_ID)));
map.put(KEY_TEXT, c.getString(c.getColumnIndex(KEY_TEXT)));
map.put(KEY_AUTHOR, c.getString(c.getColumnIndex(KEY_AUTHOR)));
map.put(KEY_PICTURE, c.getString(c.getColumnIndex(KEY_PICTURE)));
map.put(KEY_PICTURE_SDCARD, String.valueOf(c.getInt(c
.getColumnIndex(KEY_PICTURE_SDCARD))));
map.put(KEY_WEB_ID,
String.valueOf(c.getInt(c.getColumnIndex(KEY_WEB_ID))));
// adding HashList to ArrayList
quotesList.add(map);
} while (c.moveToNext());
// Getting adapter by passing xml data ArrayList
adapter = new LazyQuotesAdapter(this, quotesList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
map = quotesList.get(position);
Intent intent = new Intent(QuotesActivity.this,
QuoteDialogActivity.class);
intent.putExtra("QuoteId", map.get(KEY_ID));
intent.putExtra("quotesType", quType);
startActivity(intent);
}
});
page.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Strings to Show In Dialog with Radio Buttons
final CharSequence[] items = { "01 - 50", "51 - 100",
"101 - 150", "151 - 200", "201 - 250", "251 - 300",
"301 - 350", "351 - 400", "401 - 450", "451 - 500",
"501 - 550", "551 - 600", "601 - 650", "651 - 700",
"701 - 750", "751 - 800", "801 - 850", "851 - 900",
"901 - 950", "951 - 1000", "1001 - ..." };
pages = new ArrayList<HashMap<String, String>>();
for (int i = 0; i <= 1000; i += 50) {
HashMap<String, String> pageMap = new HashMap<String, String>();
pageMap.put("start", String.valueOf(i));
pages.add(pageMap);
}
// Creating and Building the Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(
QuotesActivity.this);
builder.setTitle("Display Quotes");
itemSelected = getIntent().getIntExtra("itemSelected", 0);
builder.setSingleChoiceItems(items, itemSelected,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int item) {
Intent intent = getIntent();
intent.putExtra("startFrom", pages
.get(item).get("start"));
intent.putExtra("startLabel", items[item]);
intent.putExtra("itemSelected", item);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(intent);
}
});
builder.setNegativeButton("Dismiss",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// action on dialog close
}
});
PageDialog = builder.create();
PageDialog.show();
}
});
} else {
}
}
// ============================================================================= =
#Override
protected void onResume() {
db.open();
super.onResume();
}
// ============================================================================= =
#Override
protected void onPause() {
db.closeDatabase();
super.onPause();
}
}
I'm getting this error:
10-06 09:09:25.466:
E/not work(1300):
pass exceptionandroid.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
my Android project pass above error when i am try to disabled button.
if (success == 1) {
Log.i("enable", "working//////");
upload.setEnabled(true);
sendDeseaseDetails.setEnabled(false);
}else{
upload.setActivated(false);
sendDeseaseDetails.setEnabled(true);
}
above code run time pass this error. what is wrong........? please help me...........!
This is full code:
package viewActivity;
//import java.io.Externalizable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.src.adms.R;
import controller.DBConnection;
//import android.R.string;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
//import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
#SuppressLint("SimpleDateFormat")
public class Send_deases_Detail extends Activity {
Spinner diseaseSpinner; // disease type
Spinner weatherSpinner; // get weather
Spinner districSpinner; // get district
Spinner soilConditionSpinner; // get soil condition
ImageButton upload; // upload images
Button clear; // clear field
Button sendDeseaseDetails; // button send disease details
int success = 0; // use, to know disease details send successfully
private Bundle extraslogin; // to get username and password
private String userName;
#SuppressWarnings("unused")
private String password;
private String userType;
private int deases_id;
private String diseaseType;
private String weather;
private String soilCondition;
private String district;
private EditText plantName;
private EditText region;
private EditText userDescription;
private static final String SEND_DESEASE_URL = "http://10.0.2.2:80/ADMS/andrioidConnection/send_deases_detail.php";
// private static final String SEND_DESEASE_URL
// ="http://admstest.netau.net/ADMS/andrioidConnection/send_deases_detail.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_USER_TYPE = "usertype";
private static final String TAG_DEASES_ID = "deases_id";
DBConnection dbConnection = new DBConnection();
private ProgressDialog dialogBox;
// private Object EditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.deases_detail);
// get user name and password form LoIin
extraslogin = getIntent().getExtras();
userName = extraslogin.getString("user_name");
password = extraslogin.getString("pass_word");
plantName = (EditText) findViewById(R.id.editPlantName);
diseaseSpinner = (Spinner) findViewById(R.id.diseaseTypeSpinner);
weatherSpinner = (Spinner) findViewById(R.id.weather_Spinner);
districSpinner = (Spinner) findViewById(R.id.district_Spinner);
soilConditionSpinner = (Spinner) findViewById(R.id.soil_condition_Spinner);
// get id of image upload button
upload = (ImageButton) findViewById(R.id.imagebtUpload);
//upload.setEnabled(false); // default set false
// get date
// ...................................................................................
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"d/M/yy h:m:s a");
String stringDate = simpleDateFormat.format(calendar.getTime());
TextView textView = (TextView) findViewById(R.id.txtDate);
textView.setText(stringDate);
// this for disease type spinner
ArrayAdapter<CharSequence> diseasearrArrayAdapter = ArrayAdapter
.createFromResource(this, R.array.diseaseType_array,
android.R.layout.simple_list_item_1);
diseasearrArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
diseaseSpinner.setAdapter(diseasearrArrayAdapter);
diseaseSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
((TextView) parent.getChildAt(0)).setTextSize(15);
// get selected item
diseaseType = parent.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// this for weather type spinner
ArrayAdapter<CharSequence> weatherArrayAdapter = ArrayAdapter
.createFromResource(this, R.array.weather_array,
android.R.layout.simple_list_item_1);
weatherArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
weatherSpinner.setAdapter(weatherArrayAdapter);
weatherSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
((TextView) parent.getChildAt(0)).setTextSize(15);
// to get selected item
weather = parent.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
// this for district spinner
ArrayAdapter<CharSequence> districArrayAdapter = ArrayAdapter
.createFromResource(this, R.array.district_array,
android.R.layout.simple_list_item_1);
districArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
districSpinner.setAdapter(districArrayAdapter);
districSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
((TextView) parent.getChildAt(0)).setTextSize(15);
// get selected item
district = parent.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
// this for soil
// condition..........................................................................................................
ArrayAdapter<CharSequence> soilArrayAdapter = ArrayAdapter
.createFromResource(this, R.array.soil_array,
android.R.layout.simple_list_item_1);
soilArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
soilConditionSpinner.setAdapter(soilArrayAdapter);
soilConditionSpinner
.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
((TextView) parent.getChildAt(0)).setTextSize(15);
// to get selected item
soilCondition = parent.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
// ..............................................................................
region = (EditText) findViewById(R.id.editRegion);
userDescription = (EditText) findViewById(R.id.editDescription);
// give action to send disease details
// button........................................................
sendDeseaseDetails = (Button) findViewById(R.id.btSendDetails);
sendDeseaseDetails.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new sendDetail().execute();
}
});
// ..............................................................................
// give action to cancel
// button...................................................................
clear = (Button) findViewById(R.id.btCancel);
clear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
clear();
//Toast.makeText(getApplicationContext(), "clear field",Toast.LENGTH_SHORT).show();
}
private void clear() {
plantName.setText("");
region.setText("");
userDescription.setText("");
upload.setEnabled(false);
sendDeseaseDetails.setEnabled(true);
weatherSpinner.setSelection(0);
soilConditionSpinner.setSelection(0);
districSpinner.setSelection(0);
diseaseSpinner.setSelection(0);
configureImageUploadButton();
}
});
clear.performClick();
}
// configure Image Upload Button......................................
private void configureImageUploadButton() {
// upload.setEnabled(true);
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click image button",
Toast.LENGTH_SHORT).show();
// pass data to image Take activity
Intent imageTakeActivity = new Intent(Send_deases_Detail.this,
ImageTakeActivity.class);
imageTakeActivity.putExtra("user_type", userType);
imageTakeActivity.putExtra("deases_id", deases_id);
success=0;
//enable();
// go to ImageTakeActivity
startActivity(imageTakeActivity);
finish();
}
});
}
// .................................................................................
protected void enable() {
if (success == 1) {
Log.i("enable", "working//////");
upload.setEnabled(true);
sendDeseaseDetails.setEnabled(false);
}else{
upload.setEnabled(false);
sendDeseaseDetails.setEnabled(true);
}
}
class sendDetail extends AsyncTask<String, String, String> {
// preprocessing part
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialogBox = new ProgressDialog(Send_deases_Detail.this);
dialogBox.setTitle("Processing...");
dialogBox.setMessage("Please wait...");
dialogBox.setIndeterminate(false);
dialogBox.setCancelable(true);
dialogBox.show();
}
// back ground run process
#Override
protected String doInBackground(String... args) {
String plant_name = plantName.getText().toString();
String region_name = region.getText().toString();
String user_discription = userDescription.getText().toString();
try {
// add first name, last name, Email & password to array list
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user_name", userName));
// params.add(new BasicNameValuePair("pass_word", password));
params.add(new BasicNameValuePair("disease_type", diseaseType));
params.add(new BasicNameValuePair("weather", weather));
params.add(new BasicNameValuePair("soil_condition",
soilCondition));
params.add(new BasicNameValuePair("district", district));
params.add(new BasicNameValuePair("plant_name", plant_name));
params.add(new BasicNameValuePair("region _name", region_name));
params.add(new BasicNameValuePair("user_discription",
user_discription));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = dbConnection.createHttpRequest(
SEND_DESEASE_URL, "POST", params);
// check your register for json response
Log.d("Send detail attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
deases_id = json.getInt(TAG_DEASES_ID);
userType = json.getString(TAG_USER_TYPE);
Log.d("deases_id", String.valueOf(deases_id));
if (success == 1) {
Log.d("Send Desease Detaiail Successful!", json.toString());
//configureImageUploadButton();//comment
Log.i("after!", "???pass configureImageUploadButton");
// configureImageUploadButton();
// finish();
// startActivity(i);
try {
enable(); // call to image button enable method
//finish();
} catch (Exception exception) {
Log.e("not work", "pass exception"+exception);
}
Log.i("work", "in back ground process......");
return json.getString(TAG_MESSAGE);
} else {
Log.d("Send detail fail!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialogBox.dismiss();
if (result != null) {
Toast.makeText(Send_deases_Detail.this, result,
Toast.LENGTH_LONG).show();
}
}
}
}
please help me
In android you need to perform any actions on views from the main UI thread. This post Running code in main thread from another thread will give you an idea of how to do so.
All the functions are running properly, but only one problem exists that if i record details for a day, and if I switch tab to the history tab to see the new record, the viewlist in the history class should display that record. However the viewlist doesnot display the lastest record, and i check the database, the lastest record has been written into database. The only way to see the new record is to close the emulator and restart it.
I found the problem that on startup, the recorder and history tab would both be initialised in OnCreate() method. But after that when I switch between these two tabs, it would not be initialised. Therefore, in the history.class, it would not open the database and read the data. That's the problem. Could somebody please help me, thanks
tab Prototype class
package com.example.tabpro;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
public class TabBar extends TabActivity{
static TabHost tabHost=null;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.tab);
tabHost = (TabHost)findViewById(android.R.id.tabhost);
tabHost = getTabHost();
Intent recorderIntent = new Intent(TabBar.this, Recorder.class);
TabSpec recorderTabSpec = tabHost.newTabSpec("tab1");
recorderTabSpec.setIndicator("Recorder");
recorderTabSpec.setContent(recorderIntent);
tabHost.addTab(recorderTabSpec);
Intent historyIntent = new Intent(TabBar.this,History.class);
TabSpec historyTabSpec = tabHost.newTabSpec("tab2");
historyTabSpec.setIndicator("History");
historyTabSpec.setContent(historyIntent);
tabHost.addTab(historyTabSpec);
tabHost.setCurrentTab(0);
}
public void switchTab(int tab)
{
tabHost.setCurrentTab(tab);
}
}
Recorder.class
package com.example.tabpro;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
public class Recorder extends Activity implements OnSeekBarChangeListener {
int mYear;
int mMonth;
int mDay;
TextView dateDisplay;
Button pickDateButton;
TextView sbHourValue;
TextView sbMinValue;
int hours;
int mins;
static final int DATE_DIALOG_ID = 0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.recorder);
initialDatePicker();
initialSeekBar();
initialSaveButton();
}
public void initialDatePicker()
{
dateDisplay = (TextView)findViewById(R.id.dateDisplay);
pickDateButton = (Button)findViewById(R.id.pickDate);
pickDateButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
final Calendar currentDate = Calendar.getInstance();
mYear = currentDate.get(Calendar.YEAR);
mMonth = currentDate.get(Calendar.MONTH);
mDay = currentDate.get(Calendar.DAY_OF_MONTH);
dateDisplay.setText(new StringBuilder()
.append(mYear).append("-")
.append(mMonth + 1).append("-")
.append(mDay));
}
public DatePickerDialog.OnDateSetListener mDateSetListener = new OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
dateDisplay.setText(new StringBuilder()
.append(mYear).append("-")
.append(mMonth + 1).append("-")//start from 0
.append(mDay));
}
};
protected Dialog onCreateDialog(int id){
switch(id)
{
case DATE_DIALOG_ID:
return new DatePickerDialog(this,mDateSetListener,mYear, mMonth, mDay);
}
return null;
}
public void initialSeekBar()
{
SeekBar sbHour = (SeekBar)findViewById(R.id.seekBar_hour);
sbHour.setMax(23);
sbHour.setProgress(0);
sbHour.setOnSeekBarChangeListener(this);
sbHourValue = (TextView)findViewById(R.id.textView_hour);
sbHourValue.setText("0"+ " hour(s)");
SeekBar sbMin = (SeekBar)findViewById(R.id.seekBar_min);
sbMin.setMax(59);
sbMin.setProgress(0);
sbMin.setOnSeekBarChangeListener(this);
sbMinValue = (TextView)findViewById(R.id.TextView_min);
sbMinValue.setText("0" + " minute(s)");
}
public void initialSaveButton()
{
Button saveButton = (Button)findViewById(R.id.button_save);
saveButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String time;
String date;
date = dateDisplay.getText().toString();
time = hours + " hour(s) " + mins + " minute(s)";
TabProDB db;
db = new TabProDB(Recorder.this);
db.open();
boolean findSameDay = false;
Cursor c = db.GetAllRecords();
if(c!=null)
{
if (c.moveToFirst())
{
do {
String dateToCompare = c.getString(c.getColumnIndex(TabProDB.KEY_DATE));
if(dateToCompare.equalsIgnoreCase(date))
{
findSameDay = true;
}
} while (c.moveToNext());
}
}
if(findSameDay!=true)
{
long id = db.insertRecord(date, time);
db.close();
Toast.makeText(Recorder.this, "Record Saved" , Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(Recorder.this, "You have already recorded the today: " + date, Toast.LENGTH_SHORT).show();
db.close();
}
switchTabInActivity(1);
}
});
}
public void switchTabInActivity(int index)
{
TabBar parentActivity;
parentActivity = (TabBar)this.getParent();
parentActivity.switchTab(index);
}
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
if(arg0.getId() == R.id.seekBar_hour){
// update hour value
hours = arg1;
sbHourValue.setText(Integer.toString(arg1)+" hour(s)");
}
else{
// update minute value
mins = arg1;
sbMinValue.setText(Integer.toString(arg1)+" minute(s)");
}
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
}
History.class
package com.example.tabpro;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class History extends Activity implements OnItemClickListener {
int getdbID;
String Date;
String Time;
ListView date_time_ListView;
ArrayList<String> listItems = null;
ArrayAdapter arrayAdapter = null;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.history);
date_time_ListView = (ListView) findViewById(R.id.listView1);
TabProDB db = new TabProDB(this);
try{
listItems = new ArrayList<String>();
db.open();
Cursor c = db.GetAllRecords();
if(c!=null)
{
if (c.moveToFirst())
{
do{
String date1 = c.getString(c.getColumnIndex(TabProDB.KEY_DATE) );
String time1 = c.getString(c.getColumnIndex(TabProDB.KEY_TIME) );
String date_time1 = date1 + "\n" +time1;
listItems.add(date_time1);
}while (c.moveToNext());
}
}
db.close();
}catch (Exception e) {}
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, listItems );
date_time_ListView.setAdapter(arrayAdapter);
date_time_ListView.setOnItemClickListener(this);
date_time_ListView.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
AlertDialog.Builder ad = new AlertDialog.Builder(History.this);
ad.setTitle("Delete?");
ad.setMessage("Are you sure you want to delete this record?");
final int positionToRemove = position;
String selectedFromList = (date_time_ListView.getItemAtPosition(position).toString());
String[] splitDateTime = selectedFromList.split("\n");
final String splitDate = splitDateTime[0];
Toast.makeText(History.this, splitDate, Toast.LENGTH_SHORT).show();
String splitTime = splitDateTime[1];
ad.setNegativeButton("Cancel", null);
ad.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
TabProDB db = new TabProDB(History.this);
try
{
db.open();
Cursor c = db.GetAllRecords();
if(c!=null)
{
if(c.moveToFirst())
{
do
{
//search database to find a date that equals the date on the listview
String findDate = c.getString(c.getColumnIndex(TabProDB.KEY_DATE));
if(splitDate.equalsIgnoreCase(findDate))
{
getdbID =c.getInt(c.getColumnIndex(TabProDB.KEY_ROWID));
db.deleteRow(getdbID);
break;
}
else
{
}
}while(c.moveToNext());
}
}
}
catch(Exception e){}
db.close();
listItems.remove(positionToRemove);
arrayAdapter.notifyDataSetChanged();
}
});
ad.show();
return false;
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
// TODO Auto-generated method stub
Intent i = new Intent(History.this, Update.class);
String str1[] = ((TextView) view).getText().toString().split("\n");
String str2 = str1[0];
String str3 = str1[1];
i.putExtra("date", str2);
i.putExtra("time", str3);
i.putExtra("position", position);
startActivity(i);
}
}
final Intent i = new Intent().setClass(TabBar.this,
Recorder.class);
TabSpec spec1 = tabHost.newTabSpec("Recoder");
spec1.setContent(i);
spec1.setIndicator(getResources().getString(R.string.title_card_post1),
getResources().getDrawable(R.drawable.tab1));
final Intent i = new Intent().setClass(TabBar.this,
History.class);
TabSpec spec1 = tabHost.newTabSpec("History");
spec1.setContent(i);
spec1.setIndicator(getResources().getString(R.string.title_card_post1),
getResources().getDrawable(R.drawable.tab1));
tabHost.addTab(spec1);
tabHost.addTab(spec2);
Try this code and let me know whether this works for you because this solution is working for me and one of my application does have it.
I'm working on an application and I've implemented sherlockListActvity to display list. But onItemClickListener is not working on this. I tried searching in internet and none of them worked for me. I did everything I found in the internet to solve this problem. Please help me on this. I'm newbie to android. The code goes like this.
NewsActivity.java
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.ministry.ensing119app.Contact;
import com.ministry.ensing119app.HomeScreen;
import com.ministry.ensing119app.R;
import com.ministry.ensing119app.bible.BibleActivity;
import com.ministry.ensing119app.donate.Donate;
import com.ministry.ensing119app.photos.GetPath;
import com.ministry.ensing119app.sermonnotes.Notes_list;
public class NewsActivity extends SherlockListActivity {
public static String url = "http://ensignweb.com/sandbox/app/comment11.php";
// JSON Node names
protected static final String TAG_PRODUCTS = "products";
protected static final String TAG_CID = "cid";
public static final String TAG_NAME = "name";
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
// contacts JSONArray
JSONArray products = null;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
actionBar = getSupportActionBar();
setContentView(R.layout.activity_news);
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
Log.d("if condition", "if condition is running");
new Message().execute(url);
// The service section
Intent intent = new Intent(this,UpdateService.class);
PendingIntent pIntent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 30000, pIntent);
startService(new Intent(this, UpdateService.class));
} else {
Log.d("if condition", "else condition is running");
Toast.makeText(getApplicationContext(), "There is no internet or low. Please check", Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent(NewsActivity.this, HomeScreen.class);
startActivity(returnIntent);
}
ListView list = getListView();
list.setClickable(true);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
TextView clickedData = (TextView) ((TextView) arg1).getText();
Toast.makeText(getApplicationContext(),
clickedData.toString(), Toast.LENGTH_SHORT).show();
}
});
}
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.news, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()){
case R.id.donate:
Intent newsIntent = new Intent(NewsActivity.this, Donate.class);
startActivity(newsIntent);
break;
case R.id.photos:
Intent photoIntent = new Intent(NewsActivity.this, GetPath.class);
startActivity(photoIntent);
break;
case R.id.notepad:
Intent notePadIntent = new Intent(NewsActivity.this, Notes_list.class);
startActivity(notePadIntent);
break;
case R.id.contact:
Intent contactIntent = new Intent(NewsActivity.this,Contact.class);
startActivity(contactIntent);
break;
case R.id.bible:
Intent BibleIntent = new Intent(NewsActivity.this, BibleActivity.class);
startActivity(BibleIntent);
break;
}
return super.onMenuItemSelected(featureId, item);
}
class Message extends AsyncTask<String, Integer, ArrayList<HashMap<String, String>> > {
ListView lv = (ListView) findViewById(android.R.id.list);
ProgressDialog progress = new ProgressDialog(NewsActivity.this);
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
#Override
protected ArrayList<HashMap<String, String>> doInBackground(String... params) {
Log.d("doInBackgound","backgound is running");
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
Log.d("path_parsing", "before parsing");
try {
// Getting Array of Contacts
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Contacts
for(int i = products.length()-1; i >=0; i--){
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String cid = c.getString(TAG_CID).toString();
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CID, cid);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
mylist.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("path_parsing", "after parsing");
return mylist;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
if(progress.isShowing()){
progress.dismiss();
}
ListAdapter adapter = new SimpleAdapter(NewsActivity.this, result , R.layout.list_item,new String[] { TAG_NAME,}, new int[] {
R.id.name});
lv.setAdapter(adapter);
lv.setTextFilterEnabled(true);
Log.d("postExecute","Postexecute is running");
lv.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Log.d("selected", String.valueOf(arg2).toString());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progress.setTitle("Progress");
progress.setMessage("Please have patience");
progress.show();
}
}
}
try this
public class NewsActivity extends SherlockListActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
ListView list = getListView();
list.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
Toast.makeText(this, "test click position: " + arg2, Toast.LENGTH_SHORT).show();
}
});
list.setAdapter(YOUR ADAPTER)
}
}
If you don't see a message, please, post your xml (activity_news.xml)