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();
}
}
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;
}
}
}
I want to get HashMap which is being passed through Bundle from a AsyncTask. But I am getting NullPointerException.
Flow is like below...
FragmentMainActivity -> TableScreenSectionwiseActivity -> GetSectionsAsync
HashMap is passed from GetSectionsAsync to TableScreenSectionwiseActivity through Bundle.
Note: FragmentMainActivity is FragmentActivity.TableScreenSectionwiseActivity is Fragment.GetSectionsAsync is a AsyncTask.
What I have tried, is like below.
Error I getting...
Error Image
TableScreenSectionwiseActivity.java
package com.malaka.ui;
import java.util.ArrayList;
import java.util.HashMap;
import adapters.table_section_adapter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.malaka.R;
import com.malaka.helper.ActionItem;
import com.malaka.helper.GetSectionsGetterSetter;
import com.malaka.helper.Logout;
import com.malaka.helper.PopupWindows;
import com.malaka.helper.QuickAction;
import com.malaka.helper.QuickActionLocation;
import com.malaka.helper.ReplaceFragment;
import com.malaka.helper.async.GetSectionsAsync;
import com.malaka.helper.async.TableStatusAsync;
import com.malaka.utils.PreferenceUtils;
public class TableScreenSectionwiseActivity extends Fragment implements
OnItemClickListener {
final static String TAG = "TableScreenSectionwiseActivity";
private static final int ID_TABLE = 1;
private static final int ID_TASK = 2;
private static final int ID_MANAGER = 3;
private static final int ID_RECIPE = 4;
private static final int ID_INSTRUCTION = 5;
private static final int ID_SEARCH = 6;
private static final int ID_HELP = 7;
private static final int ID_SETTING = 8;
private static final int ID_LOGOUT = 9;
private static final int ID_KP = 10;
private static final int ID_BANER = 20;
private static final int ID_CITY = 30;
String[] values = new String[] { "1", "2" };
public static FragmentActivity activity;
RelativeLayout rl;
static PreferenceUtils pref;
QuickAction quickAction;
QuickActionLocation quickActionLocation;
HashMap<String, ArrayList<String>> map1;
ArrayList<String> ids, names;
ListView section_list;
TextView version, malaka;
ImageView refresh;
Animation rotation;
private TextView mDropdownTitle;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.table_screen_sectionwise,
container, false);
init(view);
return view;
}
private void init(View view) {
activity = getActivity();
pref = new PreferenceUtils(getActivity());
malaka = (TextView) view
.findViewById(R.id.txt_malaka_title_table_sectionwise);
malaka.setText(pref.getLocation());
if (!pref.getSectionStatus()) {
GetSectionsAsync getSectionsAsync = new GetSectionsAsync(
getActivity());
HashMap<String, String> map = new HashMap<String, String>();
map.put("Location_Name", pref.getLocation());
getSectionsAsync.execute(map);
}
Bundle bundle = new Bundle();
Log.e("Bundle Size: ", bundle.size() + "");
map1 = (HashMap<String, ArrayList<String>>) getArguments()
.getSerializable("SECTIONS_HASHMAP");
GetSectionsGetterSetter.setData(map1);
ids = map1.get("ID_LIST");
names = map1.get("NAME_LIST");
for (int i = 0; i < names.size(); i++) {
Log.e("Names: ", names.get(i));
}
section_list = (ListView) view
.findViewById(R.id.section_name_list_view);
table_section_adapter adapter = new table_section_adapter(
activity.getApplicationContext(), values);
section_list.setAdapter(adapter);
section_list.setOnItemClickListener(this);
rl = (RelativeLayout) view.findViewById(R.id.ll_location_sectionwise);
if (pref.getUserRole()) {
rl.setVisibility(View.VISIBLE);
} else {
rl.setVisibility(View.GONE);
}
rl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
quickActionLocation.show(arg0);
}
});
version = (TextView) view.findViewById(R.id.table_version_sectionwise);
version.setText(pref.getVersion());
rotation = AnimationUtils.loadAnimation(getActivity(),
R.anim.refresh_dialog);
refresh = (ImageView) view
.findViewById(R.id.img_refresh_table_sectionwise);
refresh.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
refresh.startAnimation(rotation);
TableStatusAsync Async = new TableStatusAsync(getActivity());
HashMap<String, String> map = new HashMap<String, String>();
map.put("UserId", pref.getUserId());
map.put("SectionId", "0");
map.put("Location", pref.getLocation());
Async.execute(map);
}
});
ActionItem tableItem = new ActionItem(ID_TABLE, "Table Status");
ActionItem taskItem = new ActionItem(ID_TASK, "My Tasks");
ActionItem managerItem = new ActionItem(ID_MANAGER, "Manager");
ActionItem recipeItem = new ActionItem(ID_RECIPE, "Recipes");
ActionItem instItem = new ActionItem(ID_INSTRUCTION, "Instructions");
ActionItem searchItem = new ActionItem(ID_SEARCH, "Search");
ActionItem helpItem = new ActionItem(ID_HELP, "Help");
ActionItem settingItem = new ActionItem(ID_SETTING, "Settings");
ActionItem logoutItem = new ActionItem(ID_LOGOUT, "Logout");
ActionItem kpItem = new ActionItem(ID_KP, "Koregaon Park");
ActionItem cityItem = new ActionItem(ID_CITY, "Phoneix Market");
ActionItem banerItem = new ActionItem(ID_BANER, "Baner");
quickActionLocation = new QuickActionLocation(getActivity(),
QuickActionLocation.VERTICAL);
quickActionLocation.addActionItem(kpItem, Color.WHITE);
quickActionLocation.addActionItem(cityItem, Color.WHITE);
quickActionLocation.addActionItem(banerItem, Color.WHITE);
// use setSticky(true) to disable QuickAction dialog being dismissed
// after an item is clicked
// tableItem.setSticky(true);
// create QuickAction. Use QuickAction.VERTICAL or
// QuickAction.HORIZONTAL param to define layout
// orientation
quickAction = new QuickAction(getActivity(), QuickAction.VERTICAL);
// add action items into QuickAction
quickAction.addActionItem(tableItem, Color.WHITE);
quickAction.addActionItem(taskItem, Color.parseColor("#F2A523"));
if (pref.getUserRole()) {
quickAction.addActionItem(managerItem, Color.parseColor("#F2A523"));
}
if (pref.getRecipeScreenStatus()) {
quickAction.addActionItem(recipeItem, Color.parseColor("#F2A523"));
}
quickAction.addActionItem(instItem, Color.parseColor("#F2A523"));
quickAction.addActionItem(searchItem, Color.parseColor("#F2A523"));
quickAction.addActionItem(helpItem, Color.parseColor("#F2A523"));
quickAction.addActionItem(settingItem, Color.parseColor("#F2A523"));
quickAction.addActionItem(logoutItem, Color.parseColor("#F2A523"));
// Set listener for action item clicked
quickAction
.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
#Override
public void onItemClick(QuickAction source, int pos,
int actionId) {
ActionItem actionItem = quickAction.getActionItem(pos);
quickAction.dismiss();
// here we can filter which action item was clicked with
// pos or actionId parameter
if (actionId == ID_TABLE) {
closeDropdown();
} else if (actionId == ID_TASK) {
closeDropdown();
ReplaceFragment.getReplaceFragment(getActivity(),
new TaskLeadingActivity(), "left");
} else if (actionId == ID_MANAGER) {
closeDropdown();
ReplaceFragment.getReplaceFragment(getActivity(),
new ManagerPageActivity(), "left");
} else if (actionId == ID_RECIPE) {
closeDropdown();
ReplaceFragment.getReplaceFragment(getActivity(),
new ReceipiesScreenActivity(), "left");
} else if (actionId == ID_INSTRUCTION) {
closeDropdown();
ReplaceFragment.getReplaceFragment(getActivity(),
new InstructionActivity(), "left");
} else if (actionId == ID_SEARCH) {
closeDropdown();
} else if (actionId == ID_HELP) {
closeDropdown();
} else if (actionId == ID_SETTING) {
closeDropdown();
ReplaceFragment.getReplaceFragment(getActivity(),
new SettingScreenActivity(), "left");
} else if (actionId == ID_LOGOUT) {
closeDropdown();
Logout logout = new Logout(getActivity());
}
}
});
// set listnener for on dismiss event, this listener will be called only
// if QuickAction dialog was dismissed
// by clicking the area outside the dialog.
quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
#Override
public void onDismiss() {
// Toast.makeText(getActivity(), "Dismissed",
// Toast.LENGTH_SHORT).show();
closeDropdown();
}
});
// Set listener for action item clicked
quickActionLocation
.setOnActionItemClickListener(new QuickActionLocation.OnActionItemClickListener() {
#Override
public void onItemClick(QuickActionLocation source,
int pos, int actionId) {
ActionItem actionItem = quickActionLocation
.getActionItem(pos);
quickActionLocation.dismiss();
// here we can filter which action item was clicked with
// pos or actionId parameter
if (actionId == ID_KP) {
getTableStatus("Koregaon Park");
} else if (actionId == ID_CITY) {
getTableStatus("Phoneix Market City");
} else if (actionId == ID_BANER) {
getTableStatus("Baner");
}
}
});
mDropdownTitle = ((TextView) view
.findViewById(R.id.dropdown_textview_table_sectionwise));
mDropdownTitle.setText(pref.getUserNameToGetManagerPage()
.substring(0, 1).toUpperCase()
+ pref.getUserNameToGetManagerPage().substring(1).toLowerCase()
+ " ");
final TextView dropDownTextView = (TextView) view
.findViewById(R.id.dropdown_textview_table_sectionwise);
dropDownTextView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (PopupWindows.mWindow.isShowing()) {
closeDropdown();
} else {
openDropdown();
}
quickAction.show(v);
}
});
}
public void getTableStatus(String location) {
pref.setLocation(location);
Log.e(TAG, "location : " + pref.getLocation());
TableStatusAsync Async = new TableStatusAsync(getActivity());
HashMap<String, String> map = new HashMap<String, String>();
map.put("UserId", pref.getUserId());
map.put("SectionId", "0");
map.put("Location", pref.getLocation());
Async.execute(map);
}
private void openDropdown() {
mDropdownTitle.setCompoundDrawablesWithIntrinsicBounds(0, 0,
R.drawable.arrow_up, 0);
}
private void closeDropdown() {
mDropdownTitle.setCompoundDrawablesWithIntrinsicBounds(0, 0,
R.drawable.arrow_down, 0);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(activity, "Clicked" + position, Toast.LENGTH_SHORT)
.show();
}
}
GetSectionsAsync.java
package com.malaka.helper.async;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.malaka.helper.AsyncAttributes;
import com.malaka.helper.ReplaceFragment;
import com.malaka.helper.TableStatusXmlParser;
import com.malaka.ui.CustomerDetailsActivity;
import com.malaka.ui.TableScreenSectionwiseActivity;
import com.malaka.utils.CommanUtils;
import com.malaka.utils.NetworkUtils;
import com.malaka.utils.PreferenceUtils;
public class GetSectionsAsync extends
AsyncTask<Map<String, String>, Void, Void> {
final static String TAG = "GetSectionsAsync";
FragmentActivity context;
String xml;
HashMap<String, ArrayList<String>> details;
PreferenceUtils pref;
int response;
boolean isConnected;
public GetSectionsAsync(FragmentActivity context) {
this.context = context;
pref = new PreferenceUtils(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
CommanUtils.getDialogShow(context, "Please Wait...");
}
#Override
protected Void doInBackground(Map<String, String>... params) {
if (NetworkUtils.isConnectedToInternet(context)) {
isConnected = true;
HashMap<String, String> map = (HashMap<String, String>) params[0];
SoapObject request = new SoapObject(
AsyncAttributes.GetSecNAMESPACE,
AsyncAttributes.GetSecMETHOD_NAME);
Iterator<String> iterator = map.keySet().iterator();
PropertyInfo pi = new PropertyInfo();
pi.setName("RLocation");
pi.setValue(map.get("Location_Name"));
pi.setType(String.class);
request.addProperty(pi);
while (iterator.hasNext()) {
String key = iterator.next();
request.addProperty(key, map.get(key));
Log.e(TAG, "user id key: " + key + " value: " + map.get(key));
}
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(
AsyncAttributes.GetSecURL);
try {
androidHttpTransport.call(AsyncAttributes.GetSecSOAP_ACTION,
envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
if (result
.toString()
.equals("GetSectionsForLocationResponse{GetSectionsForLocationResult=Failur; }")) {
String xmltemp = String.valueOf(result).split("=")[1];
xml = xmltemp.split(";")[0];
} else {
String xmltemp = "<NewDataSet>\n"
+ String.valueOf(result).split("<NewDataSet>")[1];
xml = xmltemp.split("</NewDataSet>")[0] + "</NewDataSet>";
}
} catch (Exception e) {
e.printStackTrace();
}
if (xml == null) {
response = 1;
Log.e(TAG, "xml null");
} else if (xml.equals("No Table available")) {
response = 2;
} else {
response = 2;
Log.e(TAG, "Task 1 result " + xml);
details = TableStatusXmlParser.getSectionsXml(xml, context);
}
} else {
isConnected = false;
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
CommanUtils.getDialogDismiss();
if (!isConnected) {
CommanUtils.showAlertDialog("Internet Is Required", context);
} else if (response == 1) {
CommanUtils.getToast("Server Error", context);
}
if (response == 2) {
pref.setSectionStatus(true);
goAhead();
}
}
private void goAhead() {
Bundle bundle = new Bundle();
bundle.putSerializable("SECTIONS_HASHMAP", details);
Fragment fragment = new TableScreenSectionwiseActivity();
fragment.setArguments(bundle);
ReplaceFragment.getReplaceFragment(context, fragment, "");
}
}
If you guys want FragmentMainActivity code. I can put it. But I dont think so it is required. Thanks in advance.
At the end I have achieved it through INTERFACE.
Just do like below...
Make interface in GetSectionsAsync.java named FragmentInterfaceCallBack and declare a method named onTaskCompleted().
Now define a method in GetSectionsAsync.java named setFragmentInterfaceCallBack which will set the interface's object while calling from TableScreenSectionwiseActivity.java.
Now in onPostExecute method write below code....interfaceCallBack.onTaskCompleted(details); details is a data received from web service.
Go to TableScreenSectionwiseActivity.java and implements FragmentInterfaceCallBack, define it's onTaskCompleted() method and add below code to TableScreenSectionwiseActivity.java where you are calling AsyncTask getSectionsAsync.setFragmentInterfaceCallBack(this); where getSectionsAsync is a object of GetSectionsAsync.java.
In onTaskCompleted() method you get your desire data.
I have made below changes in my both files.
GetSectionsAsync.java
Making interface and defining setFragmentInterfaceCallBack() method....
private FragmentInterfaceCallBack interfaceCallBack;
public interface FragmentInterfaceCallBack {
public void onTaskCompleted(HashMap<String, ArrayList<String>> map);
}
public void setFragmentInterfaceCallBack(
FragmentInterfaceCallBack _interfaceCallBack) {
this.interfaceCallBack = _interfaceCallBack;
}
In onPostExecute method....
protected void onPostExecute(Void result) {
super.onPostExecute(result);
CommanUtils.getDialogDismiss();
if (!isConnected) {
CommanUtils.showAlertDialog("Internet Is Required", context);
} else if (response == 1) {
CommanUtils.getToast("Server Error", context);
}
if (response == 2) {
pref.setSectionStatus1(true);
// goAhead();
}
interfaceCallBack.onTaskCompleted(details);
}
TableScreenSectionwiseActivity.java
Implementing interface....
public class TableScreenSectionwiseActivity extends Fragment implements OnItemClickListener, FragmentInterfaceCallBack {
Calling AsyncTask....
if (!pref.getSectionStatus1()) {
Log.e("Once Again in TableScreenSectionwiseActivity: ", "hmm....");
GetSectionsAsync getSectionsAsync = new GetSectionsAsync(
getActivity());
getSectionsAsync.setFragmentInterfaceCallBack(this);
HashMap<String, String> map = new HashMap<String, String>();
map.put("Location_Name", pref.getLocation());
getSectionsAsync.execute(map);
}
Defining interface's method....
#Override
public void onTaskCompleted(HashMap<String, ArrayList<String>> hashMap) {
ids = hashMap.get("ID_LIST");
names = hashMap.get("NAME_LIST");
table_section_adapter adapter = new table_section_adapter(
activity.getApplicationContext(), names, ids);
section_list.setAdapter(adapter);
section_list.setOnItemClickListener(this);
}
That's it. Hope this will help someone..
Map<String, String> map = ((Bundle)appRestrictions.get(key)).keySet().stream().collect(Collectors.toMap(x -> x, x -> bundle.get(x).toString()));
JSONObject jsonNested = new JSONObject(map);
I'm trying to retrieve my data from database into checkbox list view, but I'm unable to do so. Below is the code that I'm already using to retrieve data from database into list view. But what I want is to retrieve into checkbox list view type so that I can check it. How can I do that?
public class StudentDetailActivity extends Activity implements OnClickListener, OnItemClickListener {
private ListView uGraduateNamesListView;
private Button addNewUndergraduateButton;
private ListAdapter uGraduateListAdapter;
private ArrayList<UndergraduateDetailsPojo> pojoArrayList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_detail);
uGraduateNamesListView = (ListView) findViewById(R.id.uGraduateListView);
uGraduateNamesListView.setOnItemClickListener(this);
addNewUndergraduateButton = (Button) findViewById(R.id.namesListViewAddButton);
addNewUndergraduateButton.setOnClickListener(this);
pojoArrayList = new ArrayList<UndergraduateDetailsPojo>();
uGraduateListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());
uGraduateNamesListView.setAdapter(uGraduateListAdapter);
}
#Override
public void onClick(View v) {
Intent addNewUndergraduateIntent = new Intent(this, AddNewUndergraduateActivity.class);
startActivity(addNewUndergraduateIntent);
}
public List<String> populateList(){
List<String> uGraduateNamesList = new ArrayList<String>();
AndroidOpenDbHelper openHelperClass = new AndroidOpenDbHelper(this);
SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();
Cursor cursor = sqliteDatabase.query(AndroidOpenDbHelper.TABLE_NAME_GPA, null, null, null, null, null, null);
startManagingCursor(cursor);
while (cursor.moveToNext()) {
String ugName = cursor.getString(cursor.getColumnIndex(AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_NAME));
String ugUniId = cursor.getString(cursor.getColumnIndex(AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_UNI_ID));
double ugGpa = cursor.getDouble(cursor.getColumnIndex(AndroidOpenDbHelper.COLLUMN_NAME_UNDERGRADUATE_GPA));
UndergraduateDetailsPojo ugPojoClass = new UndergraduateDetailsPojo();
ugPojoClass.setuGraduateName(ugName);
ugPojoClass.setuGraduateUniId(ugUniId);
ugPojoClass.setuGraduateGpa(ugGpa);
pojoArrayList.add(ugPojoClass);
uGraduateNamesList.add(ugName);
}
sqliteDatabase.close();
return uGraduateNamesList;
}
#Override
protected void onResume() {
super.onResume();
pojoArrayList = new ArrayList<UndergraduateDetailsPojo>();
uGraduateListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());
uGraduateNamesListView.setAdapter(uGraduateListAdapter);
}
#Override
protected void onStart() {
super.onStart();
pojoArrayList = new ArrayList<UndergraduateDetailsPojo>();
uGraduateListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());
uGraduateNamesListView.setAdapter(uGraduateListAdapter);
}
public void onClick1 (View view)
{
Intent newIntent;
newIntent=new Intent(this,HomePageActivity.class);
startActivity(newIntent);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(getApplicationContext(), "Clicked on :" + arg2, Toast.LENGTH_SHORT).show();
Intent updateDeleteUgraduateIntent = new Intent(this, UpdateDeleteUndergraduateActivity.class);
UndergraduateDetailsPojo clickedObject = pojoArrayList.get(arg2);
Bundle dataBundle = new Bundle();
dataBundle.putString("clickedUgraduateName", clickedObject.getuGraduateName());
dataBundle.putString("clickedUgraduateUniId", clickedObject.getuGraduateUniId());
dataBundle.putDouble("clickedUgraduateGpa", clickedObject.getuGraduateGpa());
updateDeleteUgraduateIntent.putExtras(dataBundle);
startActivity(updateDeleteUgraduateIntent);
}
}
You can use ListActivity Provided in Android.
You only have to manage your data to required format for this ListActivity.
You Can place action on button instead of Menu Option.
package your_package_name;
import android.app.ListActivity;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class your_activity_name extends ListActivity {
private static final int checkedItem= 0;
private String[] databaseContent;
String checkedItems = new String(); // comma separated
String uncheckedItems = new String(); // comma separated
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
databaseContent = your_data_from_database // this array should contain your data from database.
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, databaseContent));
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
menu.add(0, checkedItem, 0, R.string."String you want to show");
return result;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item)
{
switch(item.getItemId())
{
case checked:
{
int reqlength = getListAdapter().getCount();
for (int i = 0; i < reqlength ; i++)
{
if (getListView().isItemChecked(i)) {
checkedItems = checkedItems.concat(databaseContent[i]).concat(",");
}
else {
uncheckedItems = uncheckedItems.concat(databaseContent[i]).concat(",");
}
}
Thread thread = new Thread(){
#Override
public void run() {
if ( checkedItems.length() > 0 ||
uncheckedItems.length() > 0
)
{
//Here is your desired output in checkedItems & uncheckedItems
}
}
};
thread.start();
Toast.makeText(your_activity_name.this, R.string.your_string, Toast.LENGTH_SHORT).show();
finish();
return true;
}
}
return super.onMenuItemSelected(featureId, item);
}
#Override
protected void onPause()
{
super.onPause();
}
#Override
protected void onResume()
{
super.onResume();
}
}
For other way please see Link
Android ListView With Checkbox choice without using Built-in AistActivity
Hope this will resolve your problem.
It didn't showing up any error. however when I run my application, there is no result appear from my listView. I think,the mistake is because of i didn't use the correct way doing switch case statement. here is my code.
QuickSearch.java
package com.example.awesome;
import java.io.IOException;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.SQLException;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class QuickSearch extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
//-------------------------------------------------------------------------
// Initiate database data
initiateDb();
//---------------------------------------------------------------------------
// Declaration of view
final Button qsfaculty, qscollege;
super.onCreate(savedInstanceState);
setContentView(R.layout.quick_search);
//---------------------------------------------------------------------------
// Get reference
qsfaculty = (Button) this.findViewById(R.id.button1);
qsfaculty.setOnClickListener(this);
qscollege = (Button) this.findViewById(R.id.button2);
qscollege.setOnClickListener(this);
}
public void onClick(View v) {
char ch = 0;
View qsfaculty = null;
View qscollege = null;
if(v == qsfaculty){
ch = 'a';
}
else if (v == qscollege)
{ch = 'b';}
Intent i = new Intent(this,SearchLocation.class);
i.putExtra("value",ch);
startActivity(i);
}
//---------------------------------------------------------------------------
// Initiate database data
public void initiateDb() {
DatabaseHandler myDbHandler = new DatabaseHandler(this);
try {
myDbHandler.createDataBase();
}
catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHandler.openDataBase();
}
catch(SQLException sqle) {
throw sqle;
}
Log.d("Initiate", "UKM Location Count: " + myDbHandler.getUkmLocationCount());
myDbHandler.close();
}
//------------------------------------------------------------------------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quick_search, menu);
return true;
}
}
SearchLocation.java
package com.example.awesome;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class SearchLocation extends ListActivity {
//------------------------------------------------------------------
// Declaration
public static UkmLocation selectedPOI = null;
final DatabaseHandler db = new DatabaseHandler(this);
private EditText filterText = null;
ArrayAdapter<String> adapter = null;
final ArrayList<String> results = new ArrayList<String>();
final ArrayList<String> results_id = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_location);
final Intent c = new Intent(SearchLocation.this, LocationDetail.class);
//------------------------------------------------------------------
// Link editText to layout item
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
//------------------------------------------------------------------
// Reading Poi
Log.d("Reading", "Reading all Kategori ..");
int value = 0;
switch(value) {
case 'a' :
List<UkmLocation> faculty = db.getCategoryFaculty();
for(UkmLocation k : faculty) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
case 'b' :
List<UkmLocation> college = db.getCategoryCollege();
for(UkmLocation k : college) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
}
//------------------------------------------------------------------
// Set list arrayAdapter to adapter
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.textView1,results);
setListAdapter(adapter);
//------------------------------------------------------------------
// Set ListView from ListActivity
ListView lv = getListView();
lv.setTextFilterEnabled(true);
//------------------------------------------------------------------
// Set click event from listView
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
Log.d("test", "position:" + position);
Log.d("test", "actualname:" + db.getUkmLocationByName(adapter.getItem(position)).getName());
// String poiID = results_id.get(position);
String poiID = db.getUkmLocationByName(adapter.getItem(position)).getID();
setSelectedPoi(poiID);
startActivity(c);
}
});
}
private TextWatcher filterTextWatcher = 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) {
adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
public UkmLocation getSelectedPoi() {
return selectedPOI;
}
public void setSelectedPoi(String poiID) {
selectedPOI = db.getUkmLocation(poiID);
Log.d("test2", "_id:" + db.getUkmLocation(poiID).getID());
Log.d("test2", "Name:" + db.getUkmLocation(poiID).getName());
// Closing db
db.close();
}
}
i think,the if else statement inside QuickSearch.java is already correct. the problem at the switch case statement at SearchLocation.java
please help me solve this.
int value = 0;
switch(value) {
You are setting the value over which you switch to 0 so it is equivalent to doing switch(0) {...
Find out what that value is supposed to be and initialise it properly.
Also, value is of type int but your switch uses chars ('a', 'b'), so you need to either have value be a char and initialise it properly or have it be an int, initialise it properly and change your switch cases to use ints.
First you do int value = 0; so value is 0. So it is not 'a' nor 'b'.
You have to get the value from the intent as you put it in extras. i.putExtra("value",ch);
something like
char value;
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getIntgetChar("value");
}
here, i already solve my problem..
QuickSearch.java
public void onClick(View v) {
int ch = 0;
/*View qsfaculty = null;
View qscollege = null;*/
if(v == qsfaculty){
ch = '1';
}
else if (v == qscollege)
{ch = '2';}
Intent i = new Intent(this,SearchLocation.class);
i.putExtra("value",ch);
startActivity(i);
}
SearchLocation.java
Bundle extras = getIntent().getExtras();
int value = extras.getInt("value");
switch(value) {
case '1' :
List<UkmLocation> faculty = db.getCategoryFaculty();
for(UkmLocation k : faculty) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
case '2' :
List<UkmLocation> college = db.getCategoryCollege();
for(UkmLocation k : college) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
}
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