i have a listview which will retrieve detail and date from database. now im going add one textfield inside the listview. The textfield is for me to compare the date from database and count the remain day. First, i try to get the current the date to test whether can show the date in the listview or nt and i fail to show it.
package my.com.chyi.schedulev2;
import android.app.Activity;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import my.com.chyi.schedulev2.SQLController;
/**
* Created by chyi1_000 on 3/19/2015.
*/
public class assigmentActivity extends Activity {
Button addass_bt;
ListView lv;
SQLController dbcon;
TextView assID_tv,assName_tv,assAtime_tv,assRemain;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_assign);
dbcon = new SQLController(this);
dbcon.open();
//assign module
addass_bt = (Button)findViewById(R.id.addAss_bt_id);
lv =(ListView)findViewById(R.id.assList_id);
//assig module
addass_bt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent add_ass = new Intent(assigmentActivity.this,Add_Assignment.class);
startActivity(add_ass);
}
});
//assig module
Cursor cursor = dbcon.readDataA();
//calculate days different
// list -> loop
// each row different days
String[] fromA = new String[] { DBhelper.ASSIGNMENT_ID,DBhelper.ASSIGNMENT_NAME,DBhelper.ASSIGNMENT_mTime, };
int[] toA = new int[] { R.id.assigment_id, R.id.assigment_name, R.id.assigment_ATime};
SimpleCursorAdapter adapterA = new SimpleCursorAdapter(
assigmentActivity.this, R.layout.view_assignment_entry, cursor, fromA, toA);
adapterA.notifyDataSetChanged();
lv.setAdapter(adapterA);
// assig module
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
assID_tv = (TextView) view.findViewById(R.id.assigment_id);
assName_tv = (TextView) view.findViewById(R.id.assigment_name);
assAtime_tv = (TextView)view.findViewById(R.id.assigment_ATime);
Calendar d = Calendar.getInstance();
SimpleDateFormat dfd = new SimpleDateFormat("yyyy-MM-dd");
String formattedDateD = dfd.format(d.getTime().toString());
String test = formattedDateD;
String assID_val = assID_tv.getText().toString();
String assName_val = assName_tv.getText().toString();
String assATime_val = assAtime_tv .getText().toString();
Intent modify_intent = new Intent(getApplicationContext(),
Modify_assignment.class);
modify_intent.putExtra("assName", assName_val);
modify_intent.putExtra("assID", assID_val);
modify_intent.putExtra("assAtime",assATime_val);
startActivity(modify_intent);
}
});
TextView babu = (TextView) findViewById(R.id.assigment_remain);
Calendar d = Calendar.getInstance();
SimpleDateFormat dfd = new SimpleDateFormat("yyyy-MM-dd");
String formattedDateD = dfd.format(d.getTime().toString());
babu.setText(formattedDateD);
}
}
i get error at java.lang.NullPointerException at bubu.setText(formattedDateD);
may i know wht is the problem?thank for the help. my listview will auto get all the data from my SQLController, so i cannot add extra textfield in the listview.
public Cursor readDataA(){
String[] allcolumnsA = new String[] { DBhelper.ASSIGNMENT_ID,DBhelper.ASSIGNMENT_NAME,DBhelper.ASSIGNMENT_mTime};
Cursor e = database.query(DBhelper.TABLE_ASSIGNMENT, allcolumnsA,null, null, null, null, null);
if (e != null ) {
e.moveToFirst();
}
return e;
}
Try with "yyyy-MM-dd" as the pattern .
Add one 'M' to your date format
String formattedDateD = dfd.format(d.getTime()).toString();
i get error at java.lang.NullPointerException at bubu.setText(formattedDateD);
This would suggest that bubu (or babu as you have it in your code) is null.
I would take a look at this line:
TextView babu = (TextView) findViewById(R.id.assigment_remain);
This is probably not finding the view and hence returning null.
Your code needs to cope with that case and you also need to track down why you have the wrong id for your view.
Related
after testing out examples given here and here, I thought I would be able to add a score-point if the user selected the correct drop-down item. (I'm making a simple quiz app that toasts the final score).
Obviously this is too advanced for me, but I really don't want to give up and wondered if anyone might have any idea as to what I'm doing wrong please?
Here is how I have it set out in the MainActivity.java, with my failed attempts of implementing a way of checking the selected item stripped out:
First I set out the questions:
package com.example.android.arabic;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.os.Bundle;
import android.util.Log;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import com.example.android.arabic.Nature.Nature;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements OnItemSelectedListener{
int arabicScore = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// add emoji Q1
TextView q1 = findViewById(R.id.Q1_question);
q1.setText(Nature.HONEY_BEE);
// add emoji A2_option1
TextView qa2Option1 = findViewById(R.id.A2_option1);
qa2Option1.setText(Nature.GOAT);
// add emoji A2_option2
TextView qa2Option2 = findViewById(R.id.A2_option2);
qa2Option2.setText(Nature.BIRD);
// add emoji A2_option3
TextView qa2Option3 = findViewById(R.id.A2_option3);
qa2Option3.setText(Nature.HORSE);
//Q3 audio
Button q3Sound = this.findViewById(R.id.Q3_sound);
final MediaPlayer q3 = MediaPlayer.create(this, R.raw.camel);
q3Sound.setOnClickListener(new OnClickListener() {
public void onClick(View v) { q3.start();
}
});
// add emoji Q4_question
TextView q4 = findViewById(R.id.Q4_question);
q4.setText(Nature.ANT);
// Start of spinner Q4
Spinner a4 = findViewById(R.id.A4);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence>adapter = ArrayAdapter.createFromResource(this,
R.array.a4_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
a4.setAdapter(adapter);
a4.setOnItemSelectedListener(this);
//Q5 audio
Button q5Sound = this.findViewById(R.id.Q5_sound);
final MediaPlayer q5 = MediaPlayer.create(this, R.raw.cow_bird);
q5Sound.setOnClickListener(new OnClickListener() {
public void onClick(View v) { q5.start();
}
});
//A5
// add emoji A5_option1
TextView qa5Option1 = findViewById(R.id.A5_option1);
qa5Option1.setText(Nature.COW);
// add emoji A5_option2
TextView qa5Option2 = findViewById(R.id.A5_option2);
qa5Option2.setText(Nature.PIG);
// add emoji A5_option3
TextView qa5Option3 = findViewById(R.id.A5_option3);
qa5Option3.setText(Nature.SNAKE);
// add emoji A5_option4
TextView qa5Option4 = findViewById(R.id.A5_option4);
qa5Option4.setText(Nature.BIRD);
}
//Display Result
public void results(View view){
// Check point for Q1
EditText a1EditText = findViewById(R.id.A1);
String a1Entry = a1EditText.getText().toString();
if (a1Entry.contains("نحلة")) {
arabicScore = arabicScore + 1;
}
// Check point for Q2
RadioButton a2Radio = findViewById(R.id.A2_option2);
boolean isa2RadioChecked = a2Radio.isChecked();
if (isa2RadioChecked){
arabicScore = arabicScore + 1;
}
// Check point for Q3
EditText a3EditText = findViewById(R.id.A3);
String a3Entry = a3EditText.getText().toString();
if (a3Entry.contains("جمل")) {
arabicScore = arabicScore + 1;
}
// Check point for Q4
Toast resultToast = Toast.makeText(this, "You got " + arabicScore + " of 7 questions right.", Toast.LENGTH_LONG);
resultToast.show();
}
Preview of layout
}
Thank you very much for your advice in advance! I've been stuck on this for months! :'D
java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
I want to get the photo name from SQL database,then get the photo from drawable file and link the photo to a ImageView item which is inside a ListView what is the problem with following code, Please help me fix it, thank you
import android.app.ListActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class HotProduct extends ListActivity {
private ProductSQLiteHelper sqlHelper;
private SQLiteDatabase infodb;
private String[] columnsToSelect;
private String[] columnsToSelect2;
private Cursor infoCursor;
private SimpleCursorAdapter dbAdapter;
private SimpleCursorAdapter dbAdapter2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hotproduct_middle_page);
columnsToSelect = new String[] {
ProductSQLiteHelper.PRODUCT_ID,
ProductSQLiteHelper.PRODUCT_NAME,
ProductSQLiteHelper.PRODUCT_BRAND,
ProductSQLiteHelper.PRODUCT_PRICE
};
Resources res = getResources();
Log.v("Res:",String.valueOf(res));
// setTitle("Hot Product");
sqlHelper = new ProductSQLiteHelper(this);
infodb = sqlHelper.getReadableDatabase();
Cursor infoCursor= infodb.rawQuery("SELECT photo FROM phone", null);
ImageView moviePoster = (ImageView) findViewById(R.id.productPhoto);
infoCursor.moveToFirst();
if (!infoCursor.isAfterLast()) {
if (infoCursor.getInt(infoCursor.getColumnIndex(String.valueOf(ProductSQLiteHelper.PRODUCT_HOT))) == 1) {
res = this.getResources();
String posterResourceName = infoCursor.getString(infoCursor.getColumnIndex(ProductSQLiteHelper.PRODUCT_PHOTO));
Log.v("resource name",posterResourceName);
int resId = res.getIdentifier(posterResourceName, "drawable", getPackageName());
moviePoster.setImageResource(resId);
}
}
String columnsToDisplay[] = {
ProductSQLiteHelper.PRODUCT_NAME,
ProductSQLiteHelper.PRODUCT_BRAND,
ProductSQLiteHelper.PRODUCT_PRICE
// ProductSQLiteHelper.PRODUCT_PHOTO
};
int mappingToView[] = {
R.id.productName,
R.id.productBrand,
R.id.productPrice
// R.id.productPhoto
};
String args[] = {"1"};
infoCursor = infodb.query(ProductSQLiteHelper.TABLE_NAME,columnsToSelect," hot = ? ",args,null,null,null);
String posterResourceName = infoCursor.getString(infoCursor.getColumnIndex("photo"));
Log.v("resource name",posterResourceName);
dbAdapter = new SimpleCursorAdapter(this,R.layout.hotproduct_middle_page_row,infoCursor,columnsToDisplay,mappingToView,0);
setListAdapter(dbAdapter);
}
}
I found that the problems appear in
Cursor infoCursor= infodb.rawQuery("SELECT photo FROM phone", null);
ImageView moviePoster = (ImageView) findViewById(R.id.productPhoto);
infoCursor.moveToFirst();
if (!infoCursor.isAfterLast()) {
if (infoCursor.getInt(infoCursor.getColumnIndex(String.valueOf(ProductSQLiteHelper.PRODUCT_HOT))) == 1) {
res = this.getResources();
String posterResourceName = infoCursor.getString(infoCursor.getColumnIndex(ProductSQLiteHelper.PRODUCT_PHOTO));
Log.v("resource name",posterResourceName);
int resId = res.getIdentifier(posterResourceName, "drawable", getPackageName());
moviePoster.setImageResource(resId);
}
}
Your issue is due to a getColumnIndex not finding the specified column and thus returning -1 (as it does when the column is not a column). The underlying cause is that you are creating a Cursor with a single column yet in your code you are trying to access 2 columns i.e.
infoCursor.getInt(infoCursor.getColumnIndex(String.valueOf(ProductSQLiteHelper.PRODUCT_HOT)))
infoCursor.getString(infoCursor.getColumnIndex(ProductSQLiteHelper.PRODUCT_PHOTO))
The Cursor will contain just 1 column, the photo column.
I would suggest changing the SELECT clause to "SELECT * FROM phone", this will then create a Cursor with ALL columns from the table.
However, there is an additional flaw with the code in that you are not checking the result of the moveToFirst.
If the Cursor is empty then moveToFirst will return false. As the Cursor will not be after the last any attempt to retrieve data from the Cursor will fail as there is no data.
I would suggest amending your code to :-
Cursor infoCursor= infodb.rawQuery("SELECT * FROM phone", null);
ImageView moviePoster = (ImageView) findViewById(R.id.productPhoto);
while (infoCursor.moveToNext()) {
if (infoCursor.getInt(infoCursor.getColumnIndex(String.valueOf(ProductSQLiteHelper.PRODUCT_HOT))) == 1) {
res = this.getResources();
String posterResourceName = infoCursor.getString(infoCursor.getColumnIndex(ProductSQLiteHelper.PRODUCT_PHOTO));
Log.v("resource name",posterResourceName);
int resId = res.getIdentifier(posterResourceName, "drawable", getPackageName());
moviePoster.setImageResource(resId);
}
}
You may have to write code to handle an empty cursor.
how to display listview items in android, when a user enter some number in edittext and click on a button to display the specified number of list items on the next activity ?
I have one EditText and a Button on MainActivity1 and a ListView and TextView on MainActivity2. TextView is just for letting me know tht value is passing on next screen.
MainActivity.java
package com.populatelist;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText edt = (EditText)findViewById(R.id.editText1);
Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myin = new Intent(MainActivity.this,MainActivity2.class);
myin.putExtra("textbox", edt.getText().toString());
startActivity(myin);
}
});
}
}
MainActivity2.java
package com.populatelist;
import android.support.v7.app.ActionBarActivity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity2 extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
TextView tv = (TextView)findViewById(R.id.textView1);
Intent myin2 = getIntent();
String str = myin2.getStringExtra("textbox");
tv.setText(str);
final ListView lv = (ListView) findViewById(R.id.listView1);
String[] arrStr = new String[] {
"Hello World",
"Hello India",
"Hello Rajasthan",
"Hello Jodhpur",
"Hello Mujeeb"
};
final List<String> hello_list = new ArrayList<String>(Arrays.asList(arrStr));
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, hello_list);
int n = Integer.parseInt(str);
lv.setAdapter(arrayAdapter);
}
}
You can simply add the coming value at last of your string array like
String[] arrStr = new String[] {
"Hello World",
"Hello India",
"Hello Rajasthan",
"Hello Jodhpur",
"Hello Mujeeb",
str
};
It will show your input value to last position of your listview.
And if you want to add new items and show old as well then you have to pass whole string array to previous activity and add new value to last position, pass it when start next activity. By using this you can see all data on listview.
Whenever you get value in second activity create a new array "b" with required no of values.
String str = myin2.getStringExtra("textbox");
int noOfNames = Integer.parseInt(str);
String[] b = new String[StringnoOfNames];
Then copy the items from the original array
b = Arrays.copyOf(arrStr, noOfNames);
final List<String> hello_list = new ArrayList<String>(Arrays.asList(b));
First, validate if your EditText isn't null, here your app may crash
if (edt.getText().length() > 0) {
Intent myin = new Intent(MainActivity.this,MainActivity2.class);
myin.putExtra("textbox", Integer.parseInt(edt.getText().toString()));
startActivity(myin);
}
Then handle your intent
ListView lv = (ListView) findViewById(R.id.listview1);
ArrayAdapter<String> arrayAdapter = null;
int number = intent.getIntExtra("textbox", 0);
switch (number) {
case 0:
arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, arrStr);
lv.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
break;
case 1:
arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, AnotherSourceArray);
lv.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
break;
case 2:
arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, AnotherSourceArray);
lv.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
break;
...
default:
break;
}
Note - this is just sample. You can resolve this on many another ways. Each switch case may contain another data to display. Using default layouts for listviews may be frustrating, better way is to create custom class which extends ArrayAdapter<String>
I am making android app that takes user input from EditText on press of button from button.setOnClick() and use the string.getText() to search the database. But the string becomes null and no way i can send it
DbBackend.class where the search function is.
I checked and database works fine on static query which you can set to = "xyz" but no way i am able to use the user input to query the database.
Here is my code: MainActivity.java
package com.vadhod.dictcopy;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.sql.Array;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import static android.app.PendingIntent.getActivity;
public class MainActivity extends AppCompatActivity {
TextView textView;
EditText searchBar;
Button searchButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final DbBackend dbBackend = new DbBackend(MainActivity.this);
searchBar = (EditText) findViewById(R.id.searchBar);
searchButton = (Button) findViewById(R.id.searchButton);
textView = (TextView)findViewById(R.id.textView);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
String input = searchBar.getText().toString();
ArrayList<String> terms = dbBackend.getList(input);
StringBuilder builder = new StringBuilder();
for (String details : terms) {
builder.append(details + "\n");
}
textView.setText(builder.toString());
}catch (Exception e){
e.printStackTrace();
}
}
});
}
}
DbBackend.java
package com.vadhod.dictcopy;
import ...
public class DbBackend extends DatabaseObject {
public DbBackend(Context context){
super(context);
}
public ArrayList<String> getList(String search){
ArrayList<String> kWords = new ArrayList<String>();
String searchQuery = "SELECT kName FROM dictionary WHERE eName LIKE '%" + search + "%'";
try {
Cursor kCursor = this.getDbConnection().rawQuery(searchQuery, null);
if (kCursor != null){
kCursor.moveToFirst();
for (int i = 0; i < kCursor.getCount(); i++ ){
String sword = kCursor.getString(kCursor.getColumnIndexOrThrow("kName"));
kWords.add(sword);
kCursor.moveToNext();
}
kCursor.close();
return kWords;
}
return kWords;
}catch (Exception e){
e.printStackTrace();
}
return kWords;
}
}
Any help please on how to use the string when user press the search button and search that through the database and return the query?
Updated the moved code
Assuming that inside the searchButton.setOnClickListener(new View.OnClickListener() {...}); the search is working, and outside - not. The problem is your
//Option 1 not working
ArrayList<String> terms2 = dbBackend2.getList(input);
is called during the Activity setup before any view is shown to the user. So, the input is not filled at that time. You have to move this code into an onclick listener, like you did in the code above these lines.
Or provide some other source for the input.
Upd:
For the NullPointer: in your layout file activity_main you need to have a TextView with id textView. Because you do the following:
// find the textview in the layout
textView = (TextView)findViewById(R.id.textView);
// do the search, get results
...
// set textview's text, at this moment textView must not be null
textView.setText(kbuilder.toString());
This is my first time creating android app. and what i want to create now is to make a list and when a user click a name in the list the detail of the click name will show. I am trying to create simple cursor adapter. But an error occur
The constructor SimpleCursorAdapter(QuestionsNew, int, Cursor, String[], int[]) is undefined.
What do you think is the possible reason for this. Below is some part of my code
package tk.wew.wew;
import info.androidhive.sqlite.model.LocalStorage;
import info.androidhive.sqlite.model.Message;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import static tk.askd.askd.CommonUtilities.*;
public class QuestionsNew extends Fragment {
Cursor cursor;
ListView nameList;
protected ListAdapter adapter;
// TextView tvCompany = (TextView)
// findViewById(R.id.tvContactListCompany);
private static final String TAG = "Question";
private ListView list;
private static List questions;
ArrayList<String> senders = new ArrayList<String>();
ArrayList<String> shortMsg = new ArrayList<String>();
ArrayList<Integer> imageId = new ArrayList<Integer>();
SimpleCursorAdapter myCursorAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view;
//CommonUtilities.sendAQuestion(getActivity(), "msg123Kjjj11", "richmund_10023", "lofrancs1231", "Apil ka?");
questions = CommonUtilities.getAllQuestions(getActivity(), "N", null);
if(questions.size() > 0){
view = inflater.inflate(R.layout.questions_main_layout, container, false);
AskdDatabaseHelper msg_db = new AskdDatabaseHelper(getActivity());
List<Message> messages = msg_db.getAllQuestions("N", "lofrancs1231");
Cursor cursor = msg_db.getAllQuestions3();
// Setup mapping from cursor to view fields:
String[] fromFieldNames = new String[] { "KEY_MSG_MESSAGE_ID","KEY_MSG_MESSAGE" };
int[] toViewIDs = new int[] { R.id.KEY_MSG_MESSAGE_ID, R.id.KEY_MSG_MESSAGE_ID };
/* SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this, // Context
R.layout.message_list_item, // Row layout template
cursor, // cursor (set of DB records to map)
fromFieldNames, // DB Column names
toViewIDs // View IDs to put information in
);*/
myCursorAdapter = new SimpleCursorAdapter(QuestionsNew.this,
R.layout.message_list_item,
cursor,
fromFieldNames,
toViewIDs);
ListView contactList = (ListView) getView().findViewById(R.id.lvContacts);
contactList.setAdapter(myCursorAdapter);
for(int m=0; m<questions.size(); m++){
senders.add(messages.get(m).getFromUser());
shortMsg.add(messages.get(m).getMessage());
imageId.add(R.drawable.ic_launcher);
}
} else {
view = inflater.inflate(R.layout.fragments_question_new, container, false);
((TextView)view.findViewById(R.id.textView)).setText("No New Questions");
}
return view;
}
#Override
public void onStart(){
super.onStart();
Log.v(TAG, ": New onStart");
if(questions.size() > 0){
list = (ListView) getView().findViewById(R.id.list);
CustomLst adapter = new CustomLst(getActivity(), senders, imageId, shortMsg);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
// Cursor listCursor = (Cursor) parent.getItemAtPosition(position);
// Cursor listCursor = (Cursor) parent.getAdapter().getItem(position);
// Log.d("TAG", (String) parent.getItemAtPosition(id));
Toast.makeText(getActivity(),
"Position:"+ parent.getItemIdAtPosition((int) id), Toast.LENGTH_LONG)
.show();
// int message = listCursor.getInt(listCursor.getColumnIndex(AskdDatabaseHelper.KEY_MSG_MESSAGE_ID));
/*
Intent intent = new Intent(getActivity(), QuestionDetail.class);
intent.putExtra("Message_ID", listCursor.getString(listCursor.getColumnIndex(AskdDatabaseHelper.KEY_MSG_MESSAGE_ID)));
startActivity(intent);
// ListView clicked item index
int Position = position;
// ListView clicked item value
String itemValue = (String) list.getItemAtPosition(Position);
// show alert
// Toast.makeText(getActivity(),
// "Position:" + Position + " Listitem:" + itemValue, Toast.LENGTH_LONG)
// .show();
*/
}
});
} else {
Log.e(TAG, "No new question");
}
}
}
Change your constructor as below
myCursorAdapter = new SimpleCursorAdapter(getActivity(),
R.layout.message_list_item,
cursor,
fromFieldNames,
toViewIDs);
The first param is a Context. This QuestionsNew.this is not a valid context. Fragment does not extend Context.
Activity
java.lang.Object
↳ android.content.Context // check this
↳ android.content.ContextWrapper
↳ android.view.ContextThemeWrapper
↳ android.app.Activity // check this
Fragment
java.lang.Object
↳ android.app.Fragment // check this
So get context in fragment use getActivity()
public final Activity getActivity ()
Added in API level 11 Return the Activity this fragment is currently
associated with.
Also
SimpleCursorAdapter(Context context, int layout, Cursor c, String[]
from, int[] to) This constructor was deprecated in API level 11. This
option is discouraged, as it results in Cursor queries being performed
on the application's UI thread and thus can cause poor responsiveness
or even Application Not Responding errors. As an alternative, use
LoaderManager with a CursorLoader.
It is same when you use ArrayAdapter in Fragment class. The first param to the constructor of ArrayAdapter is a valid context. So even in that case you need to use getActivity() instead of FragmentName.this.