android error :ViewRootImpl$CalledFromWrongThreadException [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i know it has been asked before for a different program but I am still getting error given below for my program
Thread [Thread-15956] (Suspended (exception ViewRootImpl$CalledFromWrongThreadException))
Please HELP!!
This is my MainActivity class
package a.example.na;
import java.util.Scanner;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity {
private static TextView inputtext;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
private BluetoothDevice mDevice;
private Button findBtn;
private String address;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter == null) {
findBtn.setEnabled(false);
Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
inputtext = (TextView) findViewById(R.id.text);
findBtn = (Button)findViewById(R.id.search);
findBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView)findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
myListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View v, int pos,
long arg3) {
// Add the name and address to an array adapter to show in a ListView
String i = (String) adapterView.getItemAtPosition(pos);
B b=new B(inputtext);
b.start();
Scanner scanner = new Scanner(i);
if(scanner.hasNextLine()) {
address =scanner.nextLine();
}
mDevice = myBluetoothAdapter.getRemoteDevice(address);
scanner.close();
}
});
}
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name and the MAC address of the object to the arrayAdapter
BTArrayAdapter.add( device.getAddress()+ "\n" +device.getName() );
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(bReceiver);
}
}
This is my separate Thread class
package com.bt;
import android.widget.TextView;
public class B extends Thread {
TextView inputtext;
public B(TextView x){
inputtext=x;
}
public void run(){
inputtext.setText("hero");
}
}

Your are touching the views(widgets) in the Non UI Thread.
public class B extends Thread {
TextView inputtext;
Activity activity;
public B(Activity activity, TextView x) {
inputtext = x;
this.activity = activity;
}
public void run() {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
inputtext.setText("hero");
}
});
}
}
While starting the Thread
B b=new B(MainActivity.this, inputtext);
b.start();

Related

How to connect to a paired Bluetooth device in a List View by clicking the item

Alright so currently my app turns on bluetooth on my device and then lists all paired devices in a List View. I am trying to make it so when the item in the list view is clicked it will connect to the device (primarily for bluetooth speakers). Below i have listed my main java file with all the code that runs my app. If anyone could get me going in the right direction id appreciate it. Also this is my first project working with bluetooth.
package com.applie.itchaboynathan.appv2;
import android.support.v7.app.AppCompatActivity;
import java.io.IOException;
import java.net.Socket;
import java.util.UUID;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.view.MenuItem;
import android.widget.Toast;
import android.bluetooth.BluetoothAdapter;
import android.widget.SeekBar;
import android.widget.TextView;
import android.content.Intent;
import android.widget.ListView;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import java.util.ArrayList;
import android.widget.ArrayAdapter;
import java.util.Set;
import android.os.Handler;
public class MainActivity extends AppCompatActivity {
private static SeekBar seek_bar;
private static TextView text_view;
private BluetoothAdapter BA;
private Set<BluetoothDevice>pairedDevices;
Handler handler = new Handler();
ListView lv;
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
volumeBar();
BA = BluetoothAdapter.getDefaultAdapter();
lv = (ListView)findViewById(R.id.deviceList);
iv = (ImageView)findViewById(R.id.imgConnection);
//define menu button
ImageButton menubutton = (ImageButton)findViewById(R.id.ibtnMenu);
//enables the button to show a menu
menubutton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v){
final PopupMenu popupMenu = new PopupMenu(getApplicationContext(),v);
popupMenu.inflate(R.menu.main_menu);
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item){
switch (item.getItemId()) {
case R.id.connect:
//code for connect item
//Delay so the list creates
handler.postDelayed(new Runnable() {
#Override
public void run(){
list();
visible();
iv.setImageResource(R.mipmap.ic_checked);
}
}, 4200);
turnOn();
return true;
case R.id.disconnect:
//code for music item
turnOff();
iv.setImageResource(R.mipmap.ic_disconnected);
listClear();
return true;
case R.id.music:
//code for music item
return true;
case R.id.play:
//code for play item
return true;
case R.id.pause:
//code for pause item
return true;
}
return false;
}
});
}
});//end of button
}
//bluettoth enabler
public void turnOn(){
if (!BA.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Toast.makeText(getApplicationContext(), "Turned on",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Already on", Toast.LENGTH_LONG).show();
}
}
//bluetooth disable
public void turnOff(){
BA.disable();
Toast.makeText(getApplicationContext(), "Turned off" ,Toast.LENGTH_LONG).show();
}
public void visible(){
Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(getVisible, 0);
}
public void listClear(){
lv.setAdapter(null);
}
public void list(){
pairedDevices = BA.getBondedDevices();
ArrayList list = new ArrayList();
for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());
Toast.makeText(getApplicationContext(), "Showing Paired Devices",Toast.LENGTH_SHORT).show();
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
//volume bar code
public void volumeBar(){
seek_bar = (SeekBar)findViewById(R.id.seekBar);
text_view =(TextView)findViewById(R.id.txtVolumeLvl);
text_view.setText("Volume : " + seek_bar.getProgress() + " % ");
seek_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
int progress_value;
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progress_value = progress;
text_view.setText("Volume : " + progress + " % ");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
text_view.setText("Volume : " + progress_value + " % ");
}
}
);
}
//end volume bar
}
Try this:
ArrayList list = new ArrayList();
public void list(){
pairedDevices = BA.getBondedDevices();
for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());
Toast.makeText(getApplicationContext(), "Showing Paired Devices",Toast.LENGTH_SHORT).show();
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener () {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
String selected = list.get(position);
for (Iterator<BluetoothDevice> it = pairedDevices.iterator(); it.hasNext(); ) {
BluetoothDevice bt = it.next();
if (bt.getName().equals(selected){
//connect to device
}
}
});
}
You have use BluetoothSocketfor connecting bluetooth.
use the below code to connect.
private BluetoothAdapter mBluetoothAdarpter;
private BluetoothSocket mBtSocket;
private BluetoothDevice mBTDevice;
private static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
..
..
private boolean connectToDevice(String iAdress) {
try {
if(mBluetoothAdarpter == null) mBluetoothAdarpter = BluetoothAdapter.getDefaultAdapter();
mBTDevice = mBluetoothAdarpter.getRemoteDevice(iAdress);
mBtSocket = mBTDevice.createRfcommSocketToServiceRecord(SPP_UUID);
mBtSocket.connect();
return true;
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}

My index parameter is not working [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have been looking around for the answer but no luck on this. to resume
the id of my button is correct
Activity names are correct, but for some reason the Bundle is returning null and crashing my App, This is my Main Activity, please help.
Check the OnClick Listener I think I am using the correct form
Main Activity
package com.example.carlos.application1;
import android.widget.Button;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "MESSAGE";
private ListView obj;
DBHelper mydb;
int status = 0;
Button hp_1, HP2, fo, previous, home, next,MZ,Control,show;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new DBHelper(this);
ArrayList array_list = mydb.getAllCotacts();
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(), DisplayValues.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
hp_1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
status = 1;
Bundle bundle = new Bundle();
bundle.putInt("status", status);
Intent intent = new Intent(MainActivity.this, DisplayValues.class);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.item1:Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Intent intent = new Intent(getApplicationContext(),DisplayValues.class);
intent.putExtras(dataBundle);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
}
you haven't assigned anything to hp_1 so its value is NULL and that is the problem. You need to do the following:
hp_1 = (Button) findViewById(...);
hp_1.setOnClickListener(new View.OnClickListener() {
...

New layout doesn't pop up

I am making an app in android Studio and if you open the app on your phone you see the Launcer activity. I have a button that sends you to a new activity where te game is located. Once i click the Start button, The app closes and doesn't goes to the other activity. Why is that?
This is my code of the Launcher activity:
package joenio.sirname;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class SirName_launcher extends AppCompatActivity {
public static Button button_start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sir_name_launcher);
StartButton();
}
public void StartButton(){
button_start = (Button) findViewById(R.id.button_start);
button_start.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent("joenio.sirname.Game");
startActivity(intent1);
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_sir_name_launcher, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this is the code of the second activity:
package joenio.sirname;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import android.widget.Toast;
public class Game extends AppCompatActivity {
public static EditText editText_surname;
public static TextView textView_name;
public static Button button_check;
int x =0; //to keep track of qustions
//Context editText_this = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Displayquestions();
}
public void Displayquestions(){
final ArrayList<String> mQuestionList = new ArrayList<>();
mQuestionList.add("1+2");
mQuestionList.add("6+8");
mQuestionList.add("5 * 6");
mQuestionList.add("8*5");
mQuestionList.add("6+16");
mQuestionList.add("18-5");
textView_displayquestion.setText((mQuestionList.get(x)));//displayquestion is textview
final ArrayList<String> mAnswerList=new ArrayList<>();
mAnswerList.add("3");
mAnswerList.add("14");
mAnswerList.add("30");
mAnswerList.add("40");
mAnswerList.add("22");
mAnswerList.add("13");
//button_check is the button when user click it will first check answer and than move to next question if answer is correct
button_check.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//editText_this;
String answer = editText_ans.getText().toString();
if (answer.equals(mAnswerList.get(x))) {
x = x + 1;
textView_displayquestion.setText(mQuestionList.get(x)); //answer is correct display next quesion
Toast.makeText(getApplication().getBaseContext(),
(R.string.Nice), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication().getBaseContext(),
(R.string.tryagain), Toast.LENGTH_SHORT).show();
}
}
});
}
}
You are no where initializing your TextView and Button which must be causing NullPointerException.
Change your Game activity like this
TextView textView_displayquestion;
Button button_check;
EditText editText_ans;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
textView_displayquestion = (TextView)findViewById(R.id.displayquestion); //change as per your id
button_check = (Button)findViewById(R.id.buttoncheck); //change as per your id
editText_ans = (EditText)findViewById(R.id.answer); //change as per your id
Displayquestions();
}
In your button click , change the code as below.
Intent intent1 = new Intent(SirName_launcher.this, Game.class);
startActivity(intent1);
And also add the new Game Activity in your Manifest file too.

How to keep IOIO connected when android screen goes off?

I am using the following code with IOIO to act as a motion detector, the problem is the IOIO is disconnected whenever my phone screen goes off! I do not want the screen to stay on all the time to keep the IOIO connected!
any solution please?
package com.LookHin.ioio_pir_motion_sensor;
import ioio.lib.api.AnalogInput;
import ioio.lib.api.DigitalOutput;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.util.BaseIOIOLooper;
import ioio.lib.util.IOIOLooper;
import ioio.lib.util.android.IOIOActivity;
import android.content.Intent;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends IOIOActivity {
private ToggleButton toggleButton1;
private TextView textView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (TextView) findViewById(R.id.textView1);
toggleButton1 = (ToggleButton) findViewById(R.id.toggleButton1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.action_about:
//Toast.makeText(getApplicationContext(), "Show About", Toast.LENGTH_SHORT).show();
Intent about = new Intent(this, AboutActivity.class);
startActivity(about);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
class Looper extends BaseIOIOLooper {
private DigitalOutput digital_led0;
private AnalogInput deigital_input;
int i = 0;
private float InputStatus;
#Override
protected void setup() throws ConnectionLostException {
digital_led0 = ioio_.openDigitalOutput(0,true);
deigital_input = ioio_.openAnalogInput(45);
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "IOIO Connect", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void loop() throws ConnectionLostException {
try{
digital_led0.write(!toggleButton1.isChecked());
InputStatus = deigital_input.getVoltage();
runOnUiThread(new Runnable() {
#Override
public void run() {
textView1.setText(String.format("%.02f",InputStatus)+" v.");
if(InputStatus >= 3.0){
textView1.setBackgroundColor(Color.RED);
if (i == 0){
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
i = 1;
};
}else{
textView1.setBackgroundColor(Color.TRANSPARENT);
i = 0;
}
}
});
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
#Override
protected IOIOLooper createIOIOLooper() {
return new Looper();
}
}
Option 1) Lock the screen so it always stays awake
public void onCreate(Bundle savedInstanceState) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Option 2) Fix your response to onPause().
When the screen goes off the onPause() method is called and you should handle it as otherwise your activity will be closed.
#Override
protected void onPause() {
// Your code
super.onPause();
}
The onPause() normally calls the ioio.disconnect() so this should be overrode.
IOIOService let´s you run your code on the background even if application goes to the background.

Cannot resolve constructor

I have an error that I don't know why in my Galaxy Ace Samsung(Android 2.3.6) doesn't work but in my Motorola G (Android 4.4) works perfectly. The exception are so strange this is my code:
adapter = new SimpleCursorAdapter(this,R.layout.single_row_profession, cursor,from,to,0);
package com.orun.app;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.orun.database.DataBaseManager;
import com.orun.model.Profession;
import com.orun.s.SConnection;
public class ProfessionsActivity extends Activity {
public static SConnection sConnection;
public static DataBaseManager manager;
private static Cursor cursor;
private static ListView listView;
private static SimpleCursorAdapter adapter;
private static EditText etSearch;
private static ImageButton btSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_professions);
SharedPreferences sharedPref = getSharedPreferences(getString(R.string.PREFERENCE_FILE_KEY), Context.MODE_PRIVATE);
Toast.makeText(getApplicationContext(), "Rol "+sharedPref.getString("ROL","Estudiante"),Toast.LENGTH_LONG).show();
manager = new DataBaseManager(this);
listView = (ListView) findViewById(R.id.listView);
etSearch = (EditText)findViewById(R.id.etSearch);
new LoadTask().execute();
cursor = manager.searchProfession(etSearch.getText().toString());
int[] to = new int[]{R.id.textCode, R.id.textName,R.id.textType};
String[] from = new String[]{"_id","name","type"};
try {
adapter = new SimpleCursorAdapter(this,R.layout.single_row_profession, cursor,from,to,0);
}catch (Exception e){
e.printStackTrace();
}
listView.setAdapter(adapter);
etSearch.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
new SearchTask().execute();
adapter.changeCursor(cursor);
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {}
public void onTextChanged(CharSequence s, int start, int before,
int count) {}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(ProfessionsActivity.this,PrincipalActivity.class);
int codeProfession = Integer.parseInt(((TextView)(view.findViewById(R.id.textCode))).getText().toString());
SharedPreferences sharedPref = getSharedPreferences(getString(R.string.PREFERENCE_FILE_KEY), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("CODE_PROFESSION", codeProfession);
editor.commit();
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.professions, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class SearchTask extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
cursor = manager.searchProfession(etSearch.getText().toString());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
private class LoadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
try {
sConnection = new SConnection();
for(Profession p : sConnection.getPlansPreg())
manager.insertProfession(p.getCode(),p.getName(),"PRE");
for(Profession p : sConnection.getPlansPos())
manager.insertProfession(p.getCode(),p.getName(),"POS");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
Toast.makeText(getApplicationContext(),"Se han cargador todos los planes",Toast.LENGTH_SHORT).show();
}
}
}
The exception is: Cannot resolve constructor
'(Landroid/context/Context;ILandroid/database/Cursor;[Ljava/lang/String;[II)V
The constructor you are using was added in API level 11, so it's no wonder it doesn't exist in Android 2.3.6 (API level 10).
public SimpleCursorAdapter (Context context, int layout, Cursor c,
String[] from, int[] to, int flags) Added in API level 11
Standard constructor.
Parameters
context The context where the
ListView associated with this SimpleListItemFactory is running
layout resource identifier of a layout file that defines the views for this list item. The layout file should include at least those named views defined in "to"
c The database cursor. Can be null if the cursor is not available yet.
from A list of column names representing the data to bind to the UI. Can be null if the cursor is not available yet.
to The views that should display column in the "from" parameter. These should all be TextViews. The first N views in this list are given the values of the first N columns in the from parameter. Can be null if the cursor is not available yet.
flags Flags used to determine the behavior of the adapter, as per CursorAdapter(Context, Cursor, int).
See class reference.

Categories

Resources