Android if-else code not working properly - android

The problem i am facing is that i have my code is executing "else" block even when the "if " condition is true.
public class MsgNewPackage extends Activity {
private DatabaseHandler dbhandler;
private SimpleCursorAdapter dataAdapter;
private ListView listView;
String PKG_NAME,PKG_DUR,PKG_PRICE,PKG_ITEMS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_msg_new_package);
dbhandler = new DatabaseHandler(this);
displayListView();
}
private void displayListView()
{
String check= "Mobilink";
Intent intent = getIntent();
String conn = intent.getStringExtra("NET_CONN");
// Toast.makeText(getApplicationContext(), conn, Toast.LENGTH_SHORT).show();
if(conn == check)
{
Cursor cursor = dbhandler.fetchAllMOBSMSPackages();
String[] columns = new String[]{DatabaseHandler.KEY_PKG_NAME,DatabaseHandler.KEY_NO_OF_FREE_ITEMS,DatabaseHandler.KEY_DURATION,DatabaseHandler.KEY_CHARGES};
// the XML defined views which the data will be bound to
int[] to = new int[] { R.id.title,R.id.no_of_item,R.id.duration,R.id.pkgcharges};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(this, R.layout.list_row2, cursor,columns,to);
listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
}
else
{
Cursor cursor = dbhandler.fetchAllSMSPackages();
String[] columns = new String[]{DatabaseHandler.KEY_PKG_NAME,DatabaseHandler.KEY_NO_OF_FREE_ITEMS,DatabaseHandler.KEY_DURATION,DatabaseHandler.KEY_CHARGES};
// the XML defined views which the data will be bound to
int[] to = new int[] { R.id.title,R.id.no_of_item,R.id.duration,R.id.pkgcharges};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(this, R.layout.list_row2, cursor,columns,to);
listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
}
The toast displays that conn has "Mobilink" but the listview gets populated with results of fetchAllSMSPackages() (i.e function called in else block ) which should not be the case. Pleas help.

Try using conn.equals(check) instead of conn == check.
Strings in Java are objects, and not primitives, so you cannot compare their value using ==. This will compare the object as a whole, and not the text.

You should use .equals() when comparing String values. Not ==.
Try using:
conn.equals(check);

Related

add data to a list view from database

i want to add some info from my database to a list view, i have been able to pass that information to a textView just don't know how to get it to a list view this is my code.
public class ViewClass extends Activity{
ListView myList;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
Initialize();
Database viewAgenda = new Database(this);
viewAgenda.open();
String data = viewAgenda.getAgendaData();
viewAgenda.close();
test.Add(data);
}
private void Initialize() {
// TODO Auto-generated method stub
myList = (ListView) findViewById(R.id.panel_bottom);
}
}
You can add the data you get from the Database in ArrayList and then add this arraylist in List
ArrayList<String> list_data = new ArrayList<>();
list_data.add("item"); // likewise add list items here
ArrayAdapter<String> adapter= new ArrayAdapter<>(context, android.R.layout.activity_list_item, list_data);
myList.setAdapter(adapter);
here is Example
http://wiki.remobjects.com/wiki/Displaying_Data_with_ListView_and_BaseAdapter_(Android)
http://androidsolution4u.blogspot.in/2013/09/android-populate-listview-from-sqlite.html
may be helps you.
You must use the adapter class to link a database with a ListView. Please see the below code.
ListView lv = (ListView) findViewById(The Id of your ListView);
//fetch your data to a Cursor
Cursor c = "The result of a select statement";
SimpleCursorAdapter adap = new SimpleCursorAdapter(this,
R.layout.item2,//Your layout for the list view
c,
new String[]{"fullname", "balance"}, //field names
new int[]{R.id.rowData, R.id.rowMoney});//The ids of elements from your list view layout. The field "fullname" will be loaded into the "R.id.rowData" element.
lv.setAdapter(adap);

Using json with listview in Android

I have a dummy listview that I have setup in my app that uses the following code:
public class Roster extends Activity {
private ListView mainListView ;
private ArrayAdapter<String> listAdapter ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_roster);
// ListView resource.
mainListView = (ListView) findViewById( R.id.rosterListView );
// List of names.
String[] players = new String[] { "Dude1", "Guy2"};
ArrayList<String> playerlist = new ArrayList<String>();
playerlist.addAll( Arrays.asList(players) );
//ArrayAdapter using the list.
listAdapter = new ArrayAdapter<String>(this, R.layout.rosterrow, playerlist);
// Add more Players, If you passed a String[] instead of a List<String>
// into the ArrayAdapter constructor, you must not add more items.
// Otherwise an exception will occur.
listAdapter.add( "Person8" );
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter );
getActionBar().setDisplayHomeAsUpEnabled(true);
}
which gives me a listview of three players.
I now want to use the json object to populate the list instead of using a string. How can I populate the list using my json object?
Try to get the value of Json by key and put it in to string array.
JsonObject myjsondata = new JsonObject(jsondata.toString());
String[] players = new String[] {myjsondata.getString("key") , myjsondata.getString("key1")};

Unable to access query

I get db cannot be resloved error in this class. At the displayListView() function. Can anyone please help me solve it. Thanks
got code from here http://kdehairy.com/2012/08/19/using-a-preloaded-sqlite-database-with-sqliteopenhelper/
public class PrepopSqliteDbActivity extends Activity {
// private static final String DB_NAME = "hymnals";
//A good practice is to define database field names as constants
private SimpleCursorAdapter dataAdapter;
private Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Our key helper
ExternalDbOpenHelper repo = ExternalDbOpenHelper.getInstance( context );
SQLiteDatabase db = repo.getWritableDatabase();
displayListView();
}
private void displayListView() {
//all hymns are fetched
*final Cursor cursor = db.fetchAllHymns();*
// The desired columns to be bound
String[] columns = new String[] {
ExternalDbOpenHelper.HYMN_ID,
ExternalDbOpenHelper.HYMN_NAME,
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.tVid,
R.id.name,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.activity_main,
cursor,
columns,
to,
0);
ListView listView = (ListView) findViewById(R.id.list);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
}
});
}
}
The variable db is a local variable within the onCreate method. Use an instance variable instead:
class /* ... */ {
private SQLiteDatabase db;
/* ... */
#Override
public void onCreate(Bundle savedInstanceState) {
/* ... */
db = repo.getWritableDatabase();
/* ... */
}
/* ... */
}

NullPointerException when I run this code

So in this code, I am trying to retrieve a cursor based on the query passed through my showResults() and then create an adapter and loadermanager. I feel like the problem is being caused with the layout and id within my SimpleCursorAdapter constructor because the error started when I created the layout and id. I used Log and if statement to see whether it was the cursor that was null and nothing showed up on the logcat, so that must mean by cursor is fine.
public class SearchResultsActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private ListView list;
private DatabaseTable db;
private SimpleCursorAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_results);
db = new DatabaseTable(this);
handleIntent(getIntent());
}
public void onNewIntent(Intent intent) {
setIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
showResults(query);
}
}
private void showResults(String query) {
db = new DatabaseTable(this);
Cursor cursor = db.getContactMatches(query, null);
list = (ListView)findViewById(android.R.id.list);
mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1,
null, new String[] {DatabaseTable.COL_NAME}, new int[] {android.R.id.text1}, 0);
getLoaderManager().initLoader(0, null, this);
list.setAdapter(mAdapter);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent contactIntent = new Intent(getApplicationContext(), ContactActivity.class);
contactIntent.setData(getIntent().getData());
startActivity(contactIntent);
}
});
}
Since your code is crashing on the line list.setAdapter(mAdapter);, list is the only object that it makes sense to give you a null pointer.
Upon further examination, it is clear you are not assigning list after it is initially declared. You need to add something like this in onCreate(), after setContentView():
list = (ListView) findViewById(android.R.id.list);
(This is how you'd access it if your object had android:id="#android:id/list"; if you assigned your own ID, use R.id.your_id_here instead.)
this is probably your error here:
mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1,
null, new String[] {DatabaseTable.COL_NAME}, new int[] {android.R.id.text1}, 0);
that adapter requires a Cursor passed into the constructor at the spot where you passed null in for the parameter, like this:
mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1,
cursor, new String[] {DatabaseTable.COL_NAME}, new int[] {android.R.id.text1}, 0);
Try getting a readable database first before you query it:
db = new DatabaseTable(this);
Cursor cursor = db.getReadableDatabase().getContactMatches(query, null);

Dynamic edittext passed to string for another activity

I'm trying to setup my program to take edittext from a list view, send to a string. Then to use these strings replace text pulled from database. So depending on what the user selected first there will be between 4-10 edittext for them to fill out. Once they fill out these edittext they will click the confirm button where it takes them to the next activity. On the next activity it take these strings from the edittext where it will do some replacing of text pulled from my database. I have it working for one edittext but I want to set this up dynamically so I have a few lines take care of this function no matter how many edittext fields I had on the previous activity.
code to display edittext page in form of listview
public class editpage extends ListActivity {
public static String editstring1;
int editCount;
private dbadapter mydbhelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_list);
mydbhelper = new dbadapter(this);
mydbhelper.open();
fillData();
}
private void fillData() {
Cursor e = mydbhelper.getUserWord();
startManagingCursor(e);
// Create an array to specify the fields we want to display in the list (TITLE,DATE,NUMBER)
String[] from = new String[] {dbadapter.KEY_USERWORD,};
// an array of the views that we want to bind those fields to (in this case text1,text2,text3)
int[] to = new int[] {R.id.textType,};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter editadapter =
new SimpleCursorAdapter(this, R.layout.edit_row, e, from, to);
ListView list = getListView();
View footer = getLayoutInflater().inflate(R.layout.footer_layout, list, false);
list.addFooterView(footer);
setListAdapter(editadapter);
editCount = e.getCount();
}
public void onClick(View footer){
final MediaPlayer editClickSound = MediaPlayer.create(this, R.raw.button50);
editClickSound.start();
EditText editstory = ((EditText)findViewById(R.id.editText));
editstring1 = editstory.getText().toString();
startActivity(new Intent("wanted.pro.madlibs.OUTPUT"));
};
#Override
protected void onListItemClick(ListView list, View v, int position, long id)
{
super.onListItemClick(list, v, position, id);
}}
Next code is my output code that will display results
public class output extends ListActivity {
private dbadapter mydbhelper;
#Override
public void onCreate(Bundle savedInstantState){
super.onCreate(savedInstantState);
setContentView(R.layout.outview);
mydbhelper = new dbadapter(this);
mydbhelper.open();
fillData();
mHandler.postDelayed(mTask, 10);
}
private final Runnable mTask = new Runnable(){
public void run(){
TextView textView = (TextView)findViewById(R.id.outputText);
String story = textView.getText().toString();
CharSequence modifitedText = Replacer.replace(story,
"edit1", Html.fromHtml("<font color=\"red\">"+ editpage.editstring1 +"</font>"));
textView.setText(modifitedText);
}
};
private final Handler mHandler = new Handler();
private void fillData() {
Cursor st = mydbhelper.getStory();
startManagingCursor(st);
// Create an array to specify the fields we want to display in the list (TITLE,DATE,NUMBER)
String[] from = new String[] {dbadapter.KEY_TITLESTORY};
// an array of the views that we want to bind those fields to (in this case text1,text2,text3)
int[] to = new int[] {R.id.outputText};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this, R.layout.out_row, st, from, to);
setListAdapter(adapter);
}
}
The code in my database looks something like this
This is sample code from edit1. It will display the raw text before they user edit2 it. etc etc
Simply put I'm having trouble figuring out/finding help on how to make below code work for me dynamically
EditText editstory = ((EditText)findViewById(R.id.editText));
editstring1 = editstory.getText().toString();
CharSequence modifitedText = Replacer.replace(story,
"edit1", Html.fromHtml("<font color=\"red\">"+ editpage.editstring1 +"</font>"));
textView.setText(modifitedText);
Do you create the EditTexts in your adapter? And if you do I think you should add an onChange method to your EditTexts and handle the data from there

Categories

Resources