Java getIntent problems - java

I am new to java programming and im currently trying to pass over info to another class and display it as a TextView. I have two classes: Match and MatchResult. In Match you can push a button and a int will +1. I also have a button on the site which can make you go to the next class. In the next class i want do make the score get displayed in a TextView. But something isn't working and I don't understand why. Here is my code hope someone can help me:
Match.java:
public class Match extends Activity implements OnClickListener{
public final static String EXTRA_MESSAGE = "com.epstudios.basketballmanager_v1.MATCHRESULT";
TextView awayGoals, homeGoals, home, away;
Button homebtn, awaybtn, gotoresult;
int homecount, awaycount;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.match);
baconAndEggs();
homebtn.setOnClickListener(this);
awaybtn.setOnClickListener(this);
gotoresult.setOnClickListener(this);
}
public void sendInfo(View view) {
Intent intent = new Intent(this, Match.class);
intent.putExtra(EXTRA_MESSAGE, awaycount);
Intent homeintent = new Intent(this, Match.class);
homeintent.putExtra(EXTRA_MESSAGE, homecount);
}
private void baconAndEggs() {
awayGoals = (TextView) findViewById(R.id.Away);
homeGoals = (TextView) findViewById(R.id.Home);
homebtn = (Button) findViewById(R.id.homeBtn);
awaybtn = (Button) findViewById(R.id.awayBtn);
gotoresult = (Button) findViewById(R.id.matchResult);
}
public void counter() {
awaycount = 1;
homecount = 0;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.homeBtn:
homecount ++;
homeGoals.setText("Lakers: " + homecount);
break;
case R.id.awayBtn:
awaycount ++;
awayGoals.setText("Heat: " + awaycount);
break;
case R.id.matchResult:
Intent result = new Intent(this, MatchResult.class);
startActivity(result);
break;
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
MatchResult.java:
public class MatchResult extends Activity {
TextView home, away;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.match_result);
resultcounter();
Intent awayintent = getIntent();
String awayresult = awayintent.getStringExtra(Match.EXTRA_MESSAGE);
Intent homeintent = getIntent();
String homeresult = homeintent.getStringExtra(Match.EXTRA_MESSAGE);
home.setText(homeresult);
Log.d("Petter", homeresult);
}
The Log dosen't work

You're adding as 'Integer' putExtra("KEY", int) and retrieving as 'String' (getStringExtra)
Change sendInfo with:
public void sendInfo(View view) {
Intent intent = new Intent(this, MatchResult.class);
intent.putExtra(EXTRA_MESSAGE_AWAY, awaycount);
intent.putExtra(EXTRA_MESSAGE_HOME, homecount);
startActivituy(intent);
}
Change MatchResult with:
public class MatchResult extends Activity {
TextView home, away;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.match_result);
resultcounter();
int awayresult = getIntent().getIntExtra(Match.EXTRA_MESSAGE_AWAY, -1);
int homeresult = getIntent().getIntExtra(Match.EXTRA_MESSAGE_HOME, -1);
home.setText(String.valueOf(homeresult));
Log.d("Petter", String.valueOf(homeresult));
}

You are starting the second Activity using this:
case R.id.matchResult:
Intent result = new Intent(this, MatchResult.class);
result.putExtra(EXTRA_MESSAGE_HOME, awaycount);//Use this
result.putExtra(EXTRA_MESSAGE_AWAY, homecount);//Use this
startActivity(result);
break;
put an Intent here. Don't use 2 intents. Just put the two variables using 2 keys in same intent.
In second activity do this:
Intent intent = getIntent();
String awayresult = String.valueOf(intent.getIntExtra(Match.EXTRA_MESSAGE_AWAY, -1));
String homeresult = String.valueOf(intent.getIntExtra(Match.EXTRA_MESSAGE_HOME, -1));

Match:
public class Match extends Activity implements OnClickListener {
public final static String EXTRA_MESSAGE_HOME = "com.epstudios.basketballmanager_v1.MATCHRESULT";
public final static String EXTRA_MESSAGE_AWAY = "com.epstudios.basketballmanager_v1.MATCHRESULT";
TextView awayGoals, homeGoals, home, away;
Button homebtn, awaybtn, gotoresult;
int homecount, awaycount;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.match);
baconAndEggs();
homebtn.setOnClickListener(this);
awaybtn.setOnClickListener(this);
gotoresult.setOnClickListener(this);
}
public void sendInfo(View view) {
Intent intent = new Intent(this, MatchResult.class);
intent.putExtra(EXTRA_MESSAGE_AWAY, awaycount);
intent.putExtra(EXTRA_MESSAGE_HOME, homecount);
startActivity(intent);
}
private void baconAndEggs() {
awayGoals = (TextView) findViewById(R.id.Away);
homeGoals = (TextView) findViewById(R.id.Home);
homebtn = (Button) findViewById(R.id.homeBtn);
awaybtn = (Button) findViewById(R.id.awayBtn);
gotoresult = (Button) findViewById(R.id.matchResult);
}
public void counter() {
awaycount = 1;
homecount = 0;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.homeBtn:
homecount++;
homeGoals.setText("Lakers: " + homecount);
break;
case R.id.awayBtn:
awaycount++;
awayGoals.setText("Heat: " + awaycount);
break;
case R.id.matchResult:
Intent result = new Intent(this, MatchResult.class);
startActivity(result);
break;
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
MatchResult:
public class MatchResult extends Activity {
TextView home, away;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.match_result);
resultcounter();
int awayresult = getIntent().getIntExtra(Match.EXTRA_MESSAGE_AWAY, -1);
int homeresult = getIntent().getIntExtra(Match.EXTRA_MESSAGE_HOME, -1);
home.setText(String.valueOf(homeresult));
Log.d("Petter", String.valueOf(homeresult));
away.setText(String.valueOf(awayresult));
}
public void resultcounter() {
// TODO Auto-generated method stub
home = (TextView) findViewById(R.id.homeresult);
away = (TextView) findViewById(R.id.awayresult);
}
}

Related

Zxing Bar code scanner issue in Android

I am working on a barcode scanner App where on button click in the first Activity, I am moving to the BarcodeScanner Activity where I am importing Zxing library functionalities. Once the scanning is completed, I am moving to a 3rd Activity where I am showing the scanned Results. On clicking a button in the 3rd activity, i am coming back to the 1st activity. For devices having Marshmallow, the code is running fine. But the issue is happening with devices having versions below marshmallow where after going back to the 1st activity from the 3rd Activity, when i am pressing again the button, the scanner activity is appearing but the camera is not starting. It just showing a blank page. Please help. Below I am posting my codes for all 3 Activities.
First Activity:
public class FirstActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(Color.parseColor("#FDB50A"));
}
ImageView Scan= (ImageView) findViewById(R.id.scanButton);
Scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirstActivity.this.finish();
Intent nextPage= new Intent(FirstActivity.this,MainActivity.class);
startActivity(nextPage);
}
});
ScannerActivity:
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{
Integer response = 0 ;
int currentIndex=0;
Boolean flash=false;
DataBaseHelper dataBaseHelper;
private ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("onCreate", "onCreate");
checkPermissions();
mScannerView = new ZXingScannerView(this);
mScannerView.setResultHandler(this);
boolean cam= isCameraUsebyApp();
Log.d("cameraBar",cam+"");
if(cam)
{
mScannerView.stopCamera();
}
cam= isCameraUsebyApp();
Log.d("cameraBar",cam+"");
mScannerView.startCamera();
// FrameLayout frameLayout= new FrameLayout(this);
// FrameLayout.LayoutParams mainParam= new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
// frameLayout.setLayoutParams(mainParam);
// Button scanButton= new Button(this);
dataBaseHelper= new DataBaseHelper(this);
if(dataBaseHelper.checkDataBase()==false)
{
try {
dataBaseHelper.createDataBase();
} catch (IOException e)
{
e.printStackTrace();
}
}
else{
}
Log.d("AnimeshSQL","copy");
dataBaseHelper.openDataBase();
// List<String> data=dataBaseHelper.getQuotes("n",1);
// Log.d("AnimeshSQL",data.get(0).toString());
LayoutParams params =
new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
// scanButton.setBackground(getResources().getDrawable(R.drawable.round_button));
// scanButton.setText("Flash");
// scanButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// if(flash==false)
// {
// flash=true;
//
//
// }
// else
// {
// flash=false;
// }
// mScannerView.setFlash(flash);
// }
// });
// scanButton.setLayoutParams(params);
// frameLayout.addView(mScannerView);
// frameLayout.addView(scanButton);
// setContentView(mScannerView);
checkPermissions();
if(response == 1) {
mScannerView = null;
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
response = 0;
}
}
public boolean isCameraUsebyApp() {
Camera camera = null;
try {
camera = Camera.open();
} catch (RuntimeException e) {
return true;
} finally {
if (camera != null) camera.release();
}
return false;
}
private void checkPermissions() {
try {
for (int i = currentIndex; i < permissions.length; i++) {
currentIndex = currentIndex + 1;
int result = ContextCompat.checkSelfPermission(context, permissions[i]);
if (result == PackageManager.PERMISSION_GRANTED) {
} else {
requestPermission(permissions[i]);
return;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Activity activity = this;
Context context = this;
String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
private void requestPermission(String permission) {
//
ActivityCompat.requestPermissions(activity, new String[]{permission}, 101);
//
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 101:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//
checkPermissions();
} else {
try {
// FuncUtils.showToast(context, permissions[0] + " Denied!!!");
} catch (Exception e) {
e.printStackTrace();
}
//
///
}
break;
}
}
#Override
public void onResume() {
super.onResume();
if(response == 1) {
mScannerView = null;
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
response = 0;
}
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
public void onDestroy() {
super.onDestroy();
mScannerView.stopCamera();
}
#Override
protected void onRestart() {
super.onRestart();
Log.d("ani","onrestart");
}
#Override
public void handleResult(Result rawResult)
{
//Some codes to handle the result
Intent intent= new Intent(this,ScanResultActivity.class);
startActivity(intent);
//vbn
mScannerView.stopCamera();
MainActivity.this.finish();
}
}
Final Activity:
public class ScanResultActivity extends AppCompatActivity {
SharedPreferences prefs;
Button ok;
ImageView Hubbell,CI;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_result);
prefs = getSharedPreferences("ScanPref", MODE_PRIVATE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(Color.parseColor("#FDB50A"));
}
//Codes to show the data
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ScanResultActivity.this.finish();
Intent nextPage= new Intent(ScanResultActivity.this,FirstActivity.class);
startActivity(nextPage);
}
});
You can write Intent in OnActivityResult.
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
String message=data.getStringExtra("MESSAGE");
textView1.setText(message);
}
}

Button setText() wouldn't actually setText

I am trying to setText() to
Button btnFloor, btnTable;
Which isn't working ATM, actually I'm trying to send data from
FloorsActivity -> TablesActivity -> NewOrdersActivity
So how I pass Data from a activity to another?
FloorsActivity.java
#Override
public void onFloorItemClicked(int id) {
Intent intent = new Intent(this, TablesActivity.class);
intent.putExtra("FloorId", id);
startActivity(intent);
Toast.makeText(this, "Floor id : " + String.valueOf(id), Toast.LENGTH_SHORT).show();
}
TablesActivity.java
int floorId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_floors_tables);
initViews();
Intent intent = getIntent();
floorId = intent.getIntExtra("FloorId", 1);
}
#Override
public void onTableItemClicked(String name) {
String floorName = "F" + floorId;
Intent intent = new Intent(this, NewOrderActivity.class);
intent.putExtra("FloorId", floorId);
intent.putExtra("TableName", name);
intent.putExtra("FloorName", floorName);
startActivity(intent);
Toast.makeText(this, "Table Name : " + String.valueOf(name), Toast.LENGTH_SHORT).show();
}
NewOrderActivity.java
String floorName;
String tableName;
int floorId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_order);
initViews();
Intent intent = getIntent();
floorName = intent.getStringExtra("FloorName");
tableName = intent.getStringExtra("TableName");
floorId = intent.getIntExtra("FloorId", 1);
}
public void initViews() {
// Fetch view
btnFloor = (Button) findViewById(R.id.btn_floor);
btnTable = (Button) findViewById(R.id.btn_table);
//Set Views
btnFloor.setText(floorName);
btnTable.setText(tableName);
btnFloor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(NewOrderActivity.this, FloorsActivity.class);
startActivity(intent);
}
});
btnTable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(NewOrderActivity.this, TablesActivity.class);
intent.putExtra("FloorId", floorId);
startActivity(intent);
}
});
NewOrdersActivity is where I'm trying to set text
Here is my commit on Github for this full change
Here is the link to this project
You call initViews() before you've overloaded the intent extra's.
Fixed NewOrderActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_order);
Intent intent = getIntent();
floorName = intent.getStringExtra("FloorName");
tableName = intent.getStringExtra("TableName");
floorId = intent.getIntExtra("FloorId", 1);
initViews();
}

MQTT Implementation Issue (Dale Lane Example)

I am running into an issue with the implementation of the Dale Lane MQTT solution.
I cannot seem to figure out how to retrieve the published message from the MQTT Client I am using.
I am not sure if I am utilizing the the onReceive() method incorrectly, but for now all I would like to do is log the broadcasted messages.
http://dalelane.co.uk/blog/?p=1599
The service I have implemented is exactly as listed here, I have no errors.
public class MQTTNotifier extends Activity implements OnClickListener {
String preferenceBrokerHost, preferenceBrokerTopic;
private StatusUpdateReceiver statusUpdateIntentReceiver;
private MQTTMessageReceiver messageIntentReceiver;
private EditText etBroker, etTopic;
Button btnSubscribe, btnStopService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mqttnotifier);
initValues();
// startService();
}
private void initValues() {
btnSubscribe = (Button) findViewById(R.id.btnSubscribe);
btnSubscribe.setOnClickListener(this);
btnStopService = (Button) findViewById(R.id.btnStopService);
btnStopService.setOnClickListener(this);
// if statement to see if sharedpreferences exist, if so reopen recievers
/*
* statusUpdateIntentReceiver = new StatusUpdateReceiver(); IntentFilter intentSFilter = new
* IntentFilter(MQTTService.MQTT_STATUS_INTENT); registerReceiver(statusUpdateIntentReceiver,
* intentSFilter);
*
* messageIntentReceiver = new MQTTMessageReceiver(); IntentFilter intentCFilter = new
* IntentFilter(MQTTService.MQTT_MSG_RECEIVED_INTENT); registerReceiver(messageIntentReceiver,
* intentCFilter);
*/
}
public class StatusUpdateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle notificationData = intent.getExtras();
String newStatus = notificationData.getString(MQTTService.MQTT_STATUS_MSG);
}
}
public class MQTTMessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle notificationData = intent.getExtras();
String newTopic = notificationData.getString(MQTTService.MQTT_MSG_RECEIVED_TOPIC);
String newData = notificationData.getString(MQTTService.MQTT_MSG_RECEIVED_MSG);
Log.e("NEW TOPIC", newTopic);
Log.e("NEW DATA", newData);
}
}
#Override
protected void onDestroy() {
unregisterReceiver(statusUpdateIntentReceiver);
unregisterReceiver(messageIntentReceiver);
}
private void startService() {
Intent svc = new Intent(this, MQTTService.class);
startService(svc);
}
private void stopService() {
Intent svc = new Intent(this, MQTTService.class);
stopService(svc);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.cancel(MQTTService.MQTT_NOTIFICATION_UPDATE);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnSubscribe:
etBroker = (EditText) findViewById(R.id.etBroker);
etTopic = (EditText) findViewById(R.id.etTopic);
preferenceBrokerHost = etBroker.getText().toString().trim();
preferenceBrokerTopic = etBroker.getText().toString().trim();
createSharedPreferences(preferenceBrokerHost, preferenceBrokerTopic);
establishRecievers();
startService();
break;
case R.id.btnStopService:
stopService();
}
}
private void createSharedPreferences(String broker, String topic) {
SharedPreferences settings = getSharedPreferences(MQTTService.APP_ID, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("broker", broker);
editor.putString("topic", topic);
editor.commit();
}
private void establishRecievers() {
statusUpdateIntentReceiver = new StatusUpdateReceiver();
IntentFilter intentSFilter = new IntentFilter(MQTTService.MQTT_STATUS_INTENT);
registerReceiver(statusUpdateIntentReceiver, intentSFilter);
messageIntentReceiver = new MQTTMessageReceiver();
IntentFilter intentCFilter = new IntentFilter(MQTTService.MQTT_MSG_RECEIVED_INTENT);
registerReceiver(messageIntentReceiver, intentCFilter);
}
}
It turns out that the issue was in regards to a simple mistake that was in regards to this line.
preferenceBrokerTopic = etBroker.getText().toString().trim();
I corrected the issue and now it corrects properly because it was not subscribing to the correct topic.
preferenceBrokerTopic = etTopic.getText().toString().trim();

In Android how to fetch the contacts and save to database implements?

In My android program I have NumberList.java with list_layout.xml
In xml there is a edit text field,and a button ..in edit text we can enter a phone number and with the button we can save..
But my requirement is I want to fetch the number from contacts and save them through a button..MainActivity.java is the program which fetchs the selected contact number..But I cant save as like NumberList.java.
How can I implement???
NumberList.java
public class NumberList extends Activity implements OnClickListener{
private RemindersDbAdapter mDbAdapter;
private EditText numbr;
private Button btnAdd;
private Button btnTree;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_layout);
mDbAdapter=new RemindersDbAdapter(this);
mDbAdapter.open();
numbr=(EditText) findViewById(R.id.editNumber);
btnAdd=(Button) findViewById(R.id.btnSave);
btnAdd.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSave:
if((numbr.getText().toString()!=null)&&(numbr.getText().toString().length()>=7))
{ mDbAdapter.createReminder(numbr.getText().toString(), "", "");
mDbAdapter.close();
finish();
}
else
{
Toast.makeText(getApplicationContext(), "plz enter correct number", Toast.LENGTH_SHORT).show();
}
default:
break;
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mDbAdapter.close();
}}
and the another one which fetchs the contacts number from contact list
MainActivity.java
public class MainActivity extends Activity {
Button buttonReadContact;
TextView textPhone;
EditText ed;
final int RQS_PICKCONTACT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonReadContact = (Button)findViewById(R.id.readcontact);
textPhone = (TextView)findViewById(R.id.phone);
ed = (EditText)findViewById(R.id.phno1);
buttonReadContact.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
//Start activity to get contact
final Uri uriContact = ContactsContract.Contacts.CONTENT_URI;
Intent intentPickContact = new Intent(Intent.ACTION_PICK, uriContact);
startActivityForResult(intentPickContact, RQS_PICKCONTACT);
}});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(resultCode == RESULT_OK){
if(requestCode == RQS_PICKCONTACT){
Uri returnUri = data.getData();
Cursor cursor = getContentResolver().query(returnUri, null, null, null, null);
if(cursor.moveToNext()){
int columnIndex_ID = cursor.getColumnIndex(ContactsContract.Contacts._ID);
String contactID = cursor.getString(columnIndex_ID);
int columnIndex_HASPHONENUMBER = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
String stringHasPhoneNumber = cursor.getString(columnIndex_HASPHONENUMBER);
if(stringHasPhoneNumber.equalsIgnoreCase("1")){
Cursor cursorNum = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactID,
null,
null);
//Get the first phone number
if(cursorNum.moveToNext()){
int columnIndex_number = cursorNum.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String stringNumber = cursorNum.getString(columnIndex_number);
ed.setText(stringNumber);
}
}else{
textPhone.setText("NO Phone Number");
}
}else{
Toast.makeText(getApplicationContext(), "NO data!", Toast.LENGTH_LONG).show();
}
}
}
}
}
this is what you need just create a table and with name and phone_no and fill db details in below code
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
readContacts(getApplicationContext());
}
});
public void readContacts(Context ctx, String no) {
ContentValues cvs cvs = new ContentValues();
Cursor phones = ctx.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, ContactsContract.Contacts.DISPLAY_NAME + " ASC");
if (phones.getCount() > 0) {
while (phones.moveToNext()) {
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (!TextUtils.isEmpty(phoneNumber)) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
cvs.put("name", name );
cvs.put("phone_no", phoneNumber );
}
}
}
insertItem(cvs, "readtables");
}
private void insertItem(ContentValues cbs, String Tablename) {
SQLiteDatabase db = dbl.getWritableDatabase();
try {
CreateTablenew(Tablename);
db.insert("Tablename", null, cbs);
} catch (SQLException e) {
}
}

Send info from class to another class getIntent

I have been trying to learn java so I can program for android. I have made an app that has 2 classes, Match and MatchResult. In Match you can push a button and it will add one to a counter. At the bottom of the page i have a button that will bring you to the next class and display the counter in a textview. Im trying to send the info trough a getIntent but its something wrong that I cant find. Here is the code:
Match:
public class Match extends Activity implements OnClickListener {
public final static String EXTRA_MESSAGE_HOME = "com.epstudios.basketballmanager_v1.MATCHRESULT";
public final static String EXTRA_MESSAGE_AWAY = "com.epstudios.basketballmanager_v1.MATCHRESULT";
TextView awayGoals, homeGoals, home, away;
Button homebtn, awaybtn, gotoresult;
int homecount, awaycount;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.match);
baconAndEggs();
homebtn.setOnClickListener(this);
awaybtn.setOnClickListener(this);
gotoresult.setOnClickListener(this);
}
public void sendInfo(View view) {
Intent intent = new Intent(this, MatchResult.class);
intent.putExtra(EXTRA_MESSAGE_AWAY, awaycount);
intent.putExtra(EXTRA_MESSAGE_HOME, homecount);
startActivity(intent);
}
private void baconAndEggs() {
awayGoals = (TextView) findViewById(R.id.Away);
homeGoals = (TextView) findViewById(R.id.Home);
homebtn = (Button) findViewById(R.id.homeBtn);
awaybtn = (Button) findViewById(R.id.awayBtn);
gotoresult = (Button) findViewById(R.id.matchResult);
}
public void counter() {
awaycount = 1;
homecount = 0;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.homeBtn:
homecount++;
homeGoals.setText("Lakers: " + homecount);
break;
case R.id.awayBtn:
awaycount++;
awayGoals.setText("Heat: " + awaycount);
break;
case R.id.matchResult:
Intent result = new Intent(this, MatchResult.class);
startActivity(result);
break;
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
MatchResult:
public class MatchResult extends Activity {
TextView home, away;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.match_result);
resultcounter();
int awayresult = getIntent().getIntExtra(Match.EXTRA_MESSAGE_AWAY, -1);
int homeresult = getIntent().getIntExtra(Match.EXTRA_MESSAGE_HOME, -1);
home.setText(String.valueOf(homeresult));
Log.d("Petter", String.valueOf(homeresult));
away.setText(String.valueOf(awayresult));
}
public void resultcounter() {
// TODO Auto-generated method stub
home = (TextView) findViewById(R.id.homeresult);
away = (TextView) findViewById(R.id.awayresult);
}
}
Hmm, why not try scrapping your sendInfo() function and adding this line under your result intent instead:
result.putExtra(Match.EXTRA_MESSAGE_AWAY, awayCount);
It should work now.
It seems that code having 2 ways to call MatchResult activity hence try to use :
hasExtra() method to check whether that extra is passed with the Intent.
The constructor of Intent should have the context of your class. But in your case this refers View.OnClickListener()! So, just change it as in below.
...
case R.id.matchResult:
Intent result = new Intent(Match.this, MatchResult.class); // Like here
result.putExtra(EXTRA_MESSAGE_AWAY, awaycount);
result.putExtra(EXTRA_MESSAGE_HOME, homecount);
startActivity(result);
break;
}
...
Edit: You have never used sendInfo method. As far as I get, you could remove your sendInfo method and put those codes into switch case.
I would be create a static variable shared between activities.

Categories

Resources