Http POST request not sending - Wear OS Q&A, Help & Troubleshooting

I'm trying to build a simple app that sends data to Microsoft Azure IoT Central but I'm getting W/System.err: android.os.NetworkOnMainThreadException error.
Here is my code:
Java:
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends WearableActivity implements View.OnClickListener {
Button clickMeButton;
TextView textView;
int count = 0;
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.click_button);
button.setOnClickListener(this);
setAmbientEnabled();
}
@Override
public void onClick(View view) {
count++;
final TextView text = (TextView) findViewById(R.id.results);
text.setText("I am clicked: "+count);
int tempValue = count;
JSONObject json = new JSONObject();
try {
json.put("Count", count);
} catch (JSONException e) {
e.printStackTrace();
}
// @Deprecated HttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("URL Link");
StringEntity params = new StringEntity(json.toString());
request.addHeader("Authorization", "SharedAccessSignature Token");
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = (HttpResponse) httpClient.execute(request);
} catch (Exception ex) {
} finally {
// @Deprecated httpClient.getConnectionManager().shutdown();
Log.e("Hello", "I'm done running");
}
Here is the trace:
Code:
W/System.err: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:117)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:105)
at java.net.InetAddress.getAllByName(InetAddress.java:1154)
at org.apache.http.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:44)
W/System.err: at org.apache.http.impl.conn.DefaultClientConnectionOperator.resolveHostname(DefaultClientConnectionOperator.java:259)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:159)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:304)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:611)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:446)
at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:863)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:57)
at com.example.wearazure.MainActivity.onClick(MainActivity.java:97)
at android.view.View.performClick(View.java:6599)
at android.view.View.performClickInternal(View.java:6576)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25908)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6680)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Any suggestions are appreciated, thanks!

If you network on the main thread, the UI blocks which is bad.
You need to make a separate thread and do the networking on that. Send a message back to the UI thread when you're ready to update the UI.
Eg.
Code:
final handler = new Handler();
new Thread(() -> {
// Networking...
handler.post(() -> {
// Update UI
});
}}).start();
you can also use an async task or a service (send intent, return intent) depending on your needs. They're more work but might help to split things up better.

a1291762 said:
If you network on the main thread, the UI blocks which is bad.
You need to make a separate thread and do the networking on that. Send a message back to the UI thread when you're ready to update the UI.
Eg.
Code:
final handler = new Handler();
new Thread(() -> {
// Networking...
handler.post(() -> {
// Update UI
});
}}).start();
you can also use an async task or a service (send intent, return intent) depending on your needs. They're more work but might help to split things up better.
Click to expand...
Click to collapse
Thanks so much!!

Related

Help with ViewPager and Fragments

Hi all!
I've been developing an app that uses various things from my college and centralizes them in one app. I've made the app with two tabs - one for current students and one for prospective students. I would like to add the functionality of swiping between the two activities, and I saw that to do that, I want to convert my currentStudents and prospectiveStudents activities into fragments.
I have a couple of questions.
First, I don't quite understand how to accomplish converting the activities into fragments.
Second, I don't quite understand how to implement the viewPager effect.
If anyone can assist me in doing this, that'd be great. I've read through a lot of guides, but those guides are written to reflect other apps and it's pretty confusing.
Here is my MainActivity:
Code:
package com.andrew.obu;
import android.app.TabActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
public class MainActivity extends TabActivity {
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabHost tabHost = getTabHost();
TabSpec cstudents = tabHost.newTabSpec("Current Students");
cstudents.setIndicator("Students");
Intent cstudentsIntent = new Intent(this, CurrentStudents.class);
cstudents.setContent(cstudentsIntent);
TabSpec prospects = tabHost.newTabSpec("Prospectives");
prospects.setIndicator("Prospectives");
Intent prospectsIntent = new Intent(this, ProspectiveStudents.class);
prospects.setContent(prospectsIntent);
tabHost.addTab(cstudents);
tabHost.addTab(prospects);
tabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.BLACK);
tabHost.getTabWidget().getChildAt(1).setBackgroundColor(Color.BLACK);
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
@Override
public void onTabChanged(String arg0) {
TabHost tabHost = getTabHost();
setTabColor(tabHost);
}
});
setTabColor(tabHost);
}
public void setTabColor(TabHost tabhost) {
for(int i=0;i<tabhost.getTabWidget().getChildCount();i++)
tabhost.getTabWidget().getChildAt(i).setBackgroundColor(Color.BLACK); //unselected
if(tabhost.getCurrentTab()==0)
tabhost.getTabWidget().getChildAt(tabhost.getCurrentTab()).setBackgroundColor(Color.rgb(34, 34, 34)); //1st tab selected
else
tabhost.getTabWidget().getChildAt(tabhost.getCurrentTab()).setBackgroundColor(Color.rgb(34, 34, 34)); //2nd tab selected
}
}
And my code for the CurrentStudents Activity
Code:
package com.andrew.obu;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
public class CurrentStudents extends ListActivity {
private static final int MENU_ABOUT = 0;
private static final int MENU_CONTACT = 1;
int counter;
Button banner, email, moodle, jupiter, staff, calendar, athletics, news, prosp;
TextView display;
Drawable drawable;
@Override
public boolean onCreateOptionsMenu(android.view.Menu menu)
{
menu.add(0, MENU_ABOUT, 0, "About");
menu.add(0, MENU_CONTACT, 0, "Contact Me");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case MENU_ABOUT:
doSomething();
return true;
case MENU_CONTACT:
doSomethingElse();
return true;
}
return super.onOptionsItemSelected(item);
}
private void doSomethingElse() {
Intent intent = new Intent(getBaseContext(), Contact.class);
startActivity(intent);
}
private void doSomething() {
Intent intent = new Intent(getBaseContext(), About.class);
startActivity(intent);}
/*@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cstudents);*/
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] choose = getResources().getStringArray(R.array.cstudents_array);
ListView lv = getListView();
LayoutInflater lf;
View headerView;
lf = this.getLayoutInflater();
headerView = (View)lf.inflate(R.layout.cstudents, null, false);
lv.addHeaderView(headerView, null, false);
lv.setTextFilterEnabled(true);
lv.setBackgroundColor(Color.WHITE);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_content, choose));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent intent;
switch(position) {
default:
case 0 :
intent = new Intent(this, Bannerdisclaimer.class);
break;
case 2 :
intent = new Intent(this, Emailwebview.class);
break;
case 3 :
intent = new Intent(this, Moodlewebview.class);
break;
case 4 :
intent = new Intent(this, Jupiterwebview.class);
break;
case 5 :
intent = new Intent(this, Staffwebview.class);
break;
case 6 :
intent = new Intent(this, Calendar.class);
break;
case 7 :
intent = new Intent(this, Athleticswebview.class);
break;
case 8 :
intent = new Intent(this, Newswebview.class);
//intent7.putExtra("KEY_SELECTED_INDEX", position);
//startActivity(intent7);
break;
}
startActivity(intent);
};
}
//Resources res = getResources();
//drawable = res.getDrawable(R.drawable.bannera);
/*final Context context1 = this;
banner = (Button) findViewById(R.id.BannerButton);
banner.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
banner.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myWebView = new Intent(context1, Bannerwebview.class);
startActivity(myWebView);
}
});
final Context context2 = this;
email = (Button) findViewById(R.id.EmailButton);
email.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
email.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myWebView = new Intent(context2, Emailwebview.class);
startActivity(myWebView);
}
});
final Context context3 = this;
moodle = (Button) findViewById(R.id.MoodleButton);
moodle.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
moodle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myWebView = new Intent(context3, Moodlewebview.class);
startActivity(myWebView);
}
});
final Context context4 = this;
jupiter = (Button) findViewById(R.id.JupiterButton);
jupiter.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
jupiter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myWebView = new Intent(context4, Jupiterwebview.class);
startActivity(myWebView);
}
});
final Context context5 = this;
staff = (Button) findViewById(R.id.StaffButton);
staff.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
staff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myWebView = new Intent(context5, Staffwebview.class);
startActivity(myWebView);
}
});
final Context context = this;
calendar = (Button) findViewById(R.id.CalendarButton);
calendar.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
calendar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, Calendar.class);
startActivity(intent);
}
});
final Context context6 = this;
athletics = (Button) findViewById(R.id.AthleticsButton);
athletics.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
athletics.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context6, Athleticswebview.class);
startActivity(intent);
}
});
final Context context7 = this;
news = (Button) findViewById(R.id.NewsButton);
news.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
news.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context7, Newswebview.class);
startActivity(intent);
}
});*/
And my code for the ProspectiveStudents activity
Code:
package com.andrew.obu;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
public class ProspectiveStudents extends ListActivity
{
private static final int MENU_ABOUT = 0;
private static final int MENU_CONTACT = 1;
int counter;
Button banner, email, moodle, jupiter, staff, calendar, athletics, news, prosp;
TextView display;
Drawable drawable;
@Override
public boolean onCreateOptionsMenu(android.view.Menu menu)
{
menu.add(0, MENU_ABOUT, 0, "About");
menu.add(0, MENU_CONTACT, 0, "Contact Me");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case MENU_ABOUT:
doSomething();
return true;
case MENU_CONTACT:
doSomethingElse();
return true;
}
return super.onOptionsItemSelected(item);
}
private void doSomethingElse() {
Intent intent = new Intent(getBaseContext(), Contact.class);
startActivity(intent);
}
private void doSomething() {
Intent intent = new Intent(getBaseContext(), About.class);
startActivity(intent);}
/*@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cstudents);*/
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] choose = getResources().getStringArray(R.array.pstudents_array);
ListView lv = getListView();
LayoutInflater lf;
View headerView;
lf = this.getLayoutInflater();
headerView = (View)lf.inflate(R.layout.cstudents, null, false);
lv.addHeaderView(headerView, null, false);
lv.setTextFilterEnabled(true);
lv.setBackgroundColor(Color.WHITE);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_content, choose));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent intent;
switch(position) {
default:
case 0 :
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.okbu.edu/admissions/onlineapp.html"));
break;
case 2 :
intent = new Intent(this, Majors.class);
break;
case 3 :
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.okbu.edu/admissions/moreinfo.html"));
break;
case 4 :
intent = new Intent(this, Visitwebview.class);
break;
/*case 5 :
intent = new Intent(this, Getinvolved.class);
break;*/
}
startActivity(intent);
};
}
I recommend you to use ActionBarSherlock library: http://actionbarsherlock.com
Take a look at the samples and it will be easy to do what you ask for. At first, it may take a while to learn how to use this library, but you will not regret it since you will use it several times in the future for sure.
The coolest thing about this library is that it is compatible with older Android versions. I.e. The swipe effect will be available for Ice Cream users while for Froyo users will see two clickable tabs :good:
First of all, you can't swipe between activities. You can only swipe between fragments. Think of the activity as a container which holds your two fragments.
This is an example of a ListFragment:
Code:
public static class TitlesFragment extends ListFragment {
boolean mDualPane;
int mCurCheckPosition = 0;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Populate list with our static array of titles.
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));
// Check to see if we have a frame in which to embed the details
// fragment directly in the containing UI.
View detailsFrame = getActivity().findViewById(R.id.details);
mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
if (savedInstanceState != null) {
// Restore last state for checked position.
mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
}
if (mDualPane) {
// In dual-pane mode, the list view highlights the selected item.
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// Make sure our UI is in the correct state.
showDetails(mCurCheckPosition);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetails(position);
}
/**
* Helper function to show the details of a selected item, either by
* displaying a fragment in-place in the current UI, or starting a
* whole new activity in which it is displayed.
*/
void showDetails(int index) {
mCurCheckPosition = index;
if (mDualPane) {
// We can display everything in-place with fragments, so update
// the list to highlight the selected item and show the data.
getListView().setItemChecked(index, true);
// Check what fragment is currently shown, replace if needed.
DetailsFragment details = (DetailsFragment)
getFragmentManager().findFragmentById(R.id.details);
if (details == null || details.getShownIndex() != index) {
// Make new fragment to show this selection.
details = DetailsFragment.newInstance(index);
// Execute a transaction, replacing any existing fragment
// with this one inside the frame.
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (index == 0) {
ft.replace(R.id.details, details);
} else {
ft.replace(R.id.a_item, details);
}
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
} else {
// Otherwise we need to launch a new activity to display
// the dialog fragment with selected text.
Intent intent = new Intent();
intent.setClass(getActivity(), DetailsActivity.class);
intent.putExtra("index", index);
startActivity(intent);
}
}
}
I can't help you there because I've never worked with lists.
As for the swiping effect, build your project with a minimum SDK of 14 (ICS) and choose swipe-able tabs navigation. The ADT will do the job for you. Later, in order to maintain compatibility, use ABS library as patedit suggested.
Good luck
To implement a ViewPager, just add ViewPager to XML layout, and set a FragmentPageAdapter to it.
You must use support package from Android SDK and FragmentActivity instead of Activitiy.
You can examine source code of API Demos package to know more.

[Help]Create App

Hi Guys,
I open this thread because I need help:I would like to create an app which do a login on a website(my website)...any suggest?I'm a noob D:... ty
Try going through this tutorial
http://www.edumobile.org/android/android-development/login-request-example-in-android/
Ty so much for your answer but it helps me only at 50% ,because I would like this app connect to my website...at the moment it compare user and password insert ty to this function:
if((txtUserName.getText().toString()).equals(txtPassword.getText().toString())){
Toast.makeText(LoginRequestExample.this, "Login Successful",Toast.LENGTH_LONG).show();
} else{
Toast.makeText(LoginRequestExample.this, "Invalid Login",Toast.LENGTH_LONG).show();
}
What do I have to modify for making it compare user and password on mine online database?
ultimatexemnas said:
Ty so much for your answer but it helps me only at 50% ,because I would like this app connect to my website...at the moment it compare user and password insert ty to this function:
if((txtUserName.getText().toString()).equals(txtPassword.getText().toString())){
Toast.makeText(LoginRequestExample.this, "Login Successful",Toast.LENGTH_LONG).show();
} else{
Toast.makeText(LoginRequestExample.this, "Invalid Login",Toast.LENGTH_LONG).show();
}
What do I have to modify for making it compare user and password on mine online database?
Click to expand...
Click to collapse
I use this two methods to log on the internet. As you understand downloadUrl(URL); gives you what site tells you. I can recommend you to use special URLs in order to log in(for example example.com/auth.php?req=login&pass=....&login=....)
Code:
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
//int response = conn.getResponseCode();
//Log.d("NaviLogin", "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
Ty for you answer.
I have a noobish answer(another xD):have I to replace all myurl with the url of my website,right?>.<
ultimatexemnas said:
Ty for you answer.
I have a noobish answer(another xD):have I to replace all myurl with the url of my website,right?>.<
Click to expand...
Click to collapse
URL of your site with sonething containig your password and login and server should give you answer if your pass and login are in database or not
So,in the end it should be something like this?
package com.example.LoginRequestExample;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginRequestExample extends Activity {
EditText txtUserName;
EditText txtPassword;
Button btnLogin;
Button btnCancel; 
 @override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_request_example);
txtUserName=(EditText)this.findViewById(R.id.txtUname);
txtPassword=(EditText)this.findViewById(R.id.txtPwd);
btnLogin=(Button)this.findViewById(R.id.btnLogin);
btnLogin=(Button)this.findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if ((private String downloadUrl(String mywebsite.ukcom) throws IOException {
InputStream is = null;
int len = 500;
try {
URL url = new URL mywebsite.ukcom);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
//int response = conn.getResponseCode();
//Log.d("NaviLogin", "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
{
Toast.makeText(LoginRequestExample.this, "Invalid Login",Toast.LENGTH_LONG).show();
}
}
);
}}
Right?Are there any errors?
I've clean it up for you.
Replace google.com with your website.
Make sure your website takes username and password as a GET input.
The variable responseContent takes the result of the website after login in.
Code:
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginRequestExample extends Activity {
EditText txtUserName;
EditText txtPassword;
Button btnLogin;
Button btnCancel;
String username, password, responseContent;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_request_example);
txtUserName = (EditText) this.findViewById(R.id.txtUname);
txtPassword = (EditText) this.findViewById(R.id.txtPwd);
btnLogin = (Button) this.findViewById(R.id.btnLogin);
btnLogin = (Button) this.findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
if (txtPassword.getText().toString().trim().length() < 1
|| txtUserName.getText().toString().trim().length() < 1) {
Toast.makeText(LoginRequestExample.this,
"Please enter your login details",
Toast.LENGTH_SHORT).show();
} else {
username = txtUserName.getText().toString().trim();
password = txtPassword.getText().toString().trim();
downloadUrl("http://google.com/login.php?u=" + username + "&password=" + password);
}
}
});
}
private void downloadUrl(String myurl) throws IOException {
InputStream is = null;
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
// int response = conn.getResponseCode();
// Log.d("NaviLogin", "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
responseContent = contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
public String readIt(InputStream stream, int len) throws IOException,
UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
}

Pass Connection Between Intents

I am building an android application to do various queries on my MySQL database. Once a successful login has returned on the main activity, I create a new Intent that holds search and query options. Here's the issue I am having. I keep getting a null pointer exception on stmt = con.createStatement(); Below is my logcat:
Code:
08-20 16:12:07.359 654-810/com.android.exchange D/ExchangeService: !!! deviceId unknown; stopping self and retrying
08-20 16:12:08.469 36-653/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
08-20 16:12:11.559 1926-1949/com.example.testapplication W/System.err: java.lang.NullPointerException
08-20 16:12:11.559 1926-1949/com.example.testapplication W/System.err: at com.example.testapplication.Networking.Search(Networking.java:44)
08-20 16:12:11.559 1926-1949/com.example.testapplication W/System.err: at com.example.testapplication.ControlActivity$1.run(ControlActivity.java:53)
08-20 16:12:11.559 1926-1949/com.example.testapplication W/System.err: at java.lang.Thread.run(Thread.java:856)
08-20 16:12:12.369 654-654/com.android.exchange D/ExchangeService: !!! EAS ExchangeService, onStartCommand, startingUp = false, running = false
08-20 16:12:12.369 278-498/system_process W/ActivityManager: Unable to start service Intent { act=com.android.email.ACCOUNT_INTENT } U=0: not found
08-20 16:12:12.369 654-815/com.android.exchange D/ExchangeService: !!! Email application not found; stopping self
08-20 16:12:12.379 278-278/system_process W/ActivityManager: Unable to start service Intent { act=com.android.email.ACCOUNT_INTENT } U=0: not found
I'm curious whether it is better practice to close the connection and reopen it in the new intent? Or pass the connection between intents somehow?
Any input would be greatly appreciated!
wait...
Here are snippets of my code to help debug.
Code:
[user=439709]@override[/user]
public void onClick(View view) {
if(view.getId() == R.id.LoginButton) {
Toast.makeText(getApplicationContext(), "Attempting Connection", Toast.LENGTH_SHORT).show();
//Spawn new thread
new Thread(new Runnable() {
public void run() {
if(net.execLogin(mUserInput.getText().toString(), mPassInput.getText().toString())) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Connected to Database", Toast.LENGTH_LONG).show();
}
});
//start new activity
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
[user=439709]@override[/user]
public void run() {
Intent intent = new Intent(LoginActivity.this, ControlActivity.class);
startActivity(intent);
}
});
}
else {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Connection Failed :(", Toast.LENGTH_LONG).show();
}
});
}
}
}).start();
}
}
And here is the new activity started by the above code:
Code:
package com.example.testapplication;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class ControlActivity extends Activity implements View.OnClickListener {
private ArrayList<Hardware> list = new ArrayList<Hardware>();
EditText mEditText;
ListView mListView;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_control);
setupPage();
}
public void setupPage() {
Button search = (Button)findViewById(R.id.search);
search.setOnClickListener(this);
mEditText = (EditText)findViewById(R.id.editText);
mListView = (ListView)findViewById(R.id.listView);
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.control, menu);
return true;
}
public void onClick(View view) {
if(view.getId() == R.id.search) {
new Thread(new Runnable() {
public void run() {
list = new Networking().Search("Type", mEditText.getText().toString());
}
}).start();
ArrayAdapter<Hardware> adapter = new ArrayAdapter<Hardware>(this, android.R.layout.simple_list_item_1, list);
adapter.notifyDataSetChanged();
mListView.setAdapter(adapter);
if(list == null) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "0 Results Yielded :(", Toast.LENGTH_SHORT).show();
}
});
}
}
}
}
And here is the code I use to connect and query the database
Code:
import java.sql.*;
import java.util.*;
public class Networking implements DbQuery {
private static final String DRIVER = "org.mariadb.jdbc.Driver";
private static final String URL = "jdbc:mysql://146.187.16.32/Peirce";
ArrayList<Hardware> ara = new ArrayList<Hardware>();
Database db = new Database();
Hardware h1;
Connection con = null;
Statement stmt = null;
public boolean execLogin(String uName, String pWord) {
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL, uName, pWord);
if(!con.isClosed()){
return true;
}
return false;
}catch(SQLException e) {
e.printStackTrace();
}catch(ClassNotFoundException e) {
e.printStackTrace();
}
return false;
}
public ArrayList<Hardware> Search(String arg, String target) {
try {
stmt = con.createStatement(); //throws null pointer exception
ResultSet rs = stmt.executeQuery("Select * from " + db.getTable() + " where " + arg + "='" + target + "';");
while(rs.next()) {
ara.add(new Hardware(rs.getString("Type"), rs.getString("Make"), rs.getString("Model"), rs.getString("Serial"), rs.getString("Comments")));
}
return ara;
}catch(SQLException e) {
e.printStackTrace();
}catch(NullPointerException e) {
e.printStackTrace();
}
return ara;
}
nevermind
i have figured it out.

Updating tabs to new tab fragments

Hi all,
I had an app that was working about 3 years ago that I decided to update for the latest android sdk.I was using tabs but have decided to update to tab fragments with swipe.The problem I'm having is how to lay out the code.I have updated my app but have a few errors.Specifically the Book Now tab usually has a book now form so people can fill it out and upon clicking submit it sms's it to me.Below is the code for BookNowFragmnet.java.
I should mention that the tab and swipe part works flawlessly.I dont have a logcat because it wont build without removing the code
PHP:
package com.deano.dfw;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class BookNowFragment extends Fragment implements OnClickListener {
Button buttonSubmit;
EditText edittextPhone;
EditText editTextProblem;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_booknow, container, false);
buttonSubmit = (Button) rootView.findViewById(R.id.buttonSubmit);
edittextPhone = (EditText) rootView.findViewById(R.id.edittextPhone);
editTextProblem = (EditText) rootView.findViewById(R.id.editTextProblem);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String phoneNo = edittextPhone.getText().toString();
String message = editTextProblem.getText().toString();
if (phoneNo.length()>0 && message.length()>0)
sendSMS(phoneNo, message);
else
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
// ---sends a SMS message to another device---
private void sendSMS(String phoneNumber, String message) {
/*
* PendingIntent pi = PendingIntent.getActivity(this, 0, new
* Intent(this, test.class), 0); SmsManager sms =
* SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null,
* message, pi, null);
*/
String SENT = "SMS_SENT";
// String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
SENT), 0);
/*
* PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new
* Intent(DELIVERED), 0);
*/
// ---when the SMS has been sent---
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
The problem areas are as follows;
1. getBaseContext has the error "The method getBaseContext is undefined for the type new View.OnClickListener"
PHP:
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
2. getBroadcast has the error "The method getBroadcast(Context, int, Intent, int) in the type PendingIntent is not applicable for the arguments (BookNowFragment, int, Intent, int)"
PHP:
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
3.registerReceiver has the error "The method registerReceiver(new BroadcastReceiver(){}, IntentFilter) is undefined for the type BookNowFragment"
PHP:
// ---when the SMS has been sent---
registerReceiver(new BroadcastReceiver() {
4. all of the getBaseContext under the following have the error "The method getBaseContext() is undefined for the type new BroadcastReceiver"
PHP:
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
any help would be appreciated I have searched for the last two days trying different things.
dfwcomputer said:
1. getBaseContext has the error "The method getBaseContext is undefined for the type new View.OnClickListener"
PHP:
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
Click to expand...
Click to collapse
So you are asking for the method "getBaseContext" within an onClickListener... it does not have a method called that... like it's telling you it's undefined
It would probably be a better idea to use application context either by direct use of getApplicationContext or by a "final" reference maybe...
dfwcomputer said:
2. getBroadcast has the error "The method getBroadcast(Context, int, Intent, int) in the type PendingIntent is not applicable for the arguments (BookNowFragment, int, Intent, int)"
PHP:
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
Click to expand...
Click to collapse
BookNowFragment is not extended from the base type of Context that is expected in the arguments.
dfwcomputer said:
3.registerReceiver has the error "The method registerReceiver(new BroadcastReceiver(){}, IntentFilter) is undefined for the type BookNowFragment"
PHP:
// ---when the SMS has been sent---
registerReceiver(new BroadcastReceiver() {
Click to expand...
Click to collapse
dfwcomputer said:
4. all of the getBaseContext under the following have the error "The method getBaseContext() is undefined for the type new BroadcastReceiver"
PHP:
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
any help would be appreciated I have searched for the last two days trying different things.
Click to expand...
Click to collapse
Actually the last to are just repeats of the previous really... I'm guessing here but it seems you may have skipped ahead of where you should be in a learning sense.. cause it seems to be like your running without being knowing how to jog kinda thing. Not attempting to be condescending, just I'm a trainer and always attempt to point this stuff out when I see it
Maybe go back and do some of the basics again, and include fragments etc
thanks, Im well aware i'm running before im born but this is the only app I intend to write as it's specifically for my business.
dfwcomputer said:
thanks, Im well aware i'm running before im born but this is the only app I intend to write as it's specifically for my business.
Click to expand...
Click to collapse
hmmm, well if thats all thats wrong with it, all I could offer is for you to send me the packaged src+res and I will have a look... if it takes less than 20 min to fix and get running I have no problem fixing it for you. If it doesn't and maybe takes longer then I may have to leave it. Should be quick though, up to you
But with the info I gave you should be able to fix those 4 issues...if not hit me up on hangouts and will talk you though it
thanks m8.Ill play around today but if I cant figure it out I might get you to have a look if time permits.I develop in eclipse.Is it a matter of just zipping up the project folder?
dfwcomputer said:
thanks m8.Ill play around today but if I cant figure it out I might get you to have a look if time permits.I develop in eclipse.Is it a matter of just zipping up the project folder?
Click to expand...
Click to collapse
Yeah, just zip the project.
But like I say just get a reference to the activity to use as the "context" part of the argument, either where you need it or as a final reference or member variable
so getActivity()
or memberVar
Context mContext = null;
(in onCreate) mContext = getActivity();
or as final
final Context c = getActivity();
deanwray said:
Yeah, just zip the project.
But like I say just get a reference to the activity to use as the "context" part of the argument, either where you need it or as a final reference or member variable
so getActivity()
or memberVar
Context mContext = null;
(in onCreate) mContext = getActivity();
or as final
final Context c = getActivity();
Click to expand...
Click to collapse
lol now I have less faith ill be fixing it..... Ill let you know thanks again
sent you a private message m8, because there is some personal info in the app
dfwcomputer said:
sent you a private message m8, because there is some personal info in the app
Click to expand...
Click to collapse
fixed and sent private msg with class
Thanks again, I apreciate it.I have changed the personal info and posted the working code here incase someone else has a similar issue.
PHP:
package com.deano.dfw;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class BookNowFragment extends Fragment implements OnClickListener {
Button buttonSubmit;
EditText edittextPhone;
EditText editTextProblem;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_booknow, container, false);
buttonSubmit = (Button) rootView.findViewById(R.id.buttonSubmit);
//edittextPhone = (EditText) rootView.findViewById(R.id.edittextPhone);
//editTextProblem = (EditText) rootView.findViewById(R.id.editTextProblem);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String strPhoneNo = "0000000000";
TextView txtName = (TextView) rootView.findViewById(R.id.edittextName);
TextView txtPhone = (TextView) rootView.findViewById(R.id.edittextPhone);
TextView txtProblem = (TextView) rootView.findViewById(R.id.editTextProblem);
String strName = "Name: " + txtName.getText().toString();
String strPhone = "Phone: " + txtPhone.getText().toString();
String strProblem = "Problem: "
+ txtProblem.getText().toString();
String strMessage = strName + "\n" + strPhone + "\n"
+ strProblem;
BookNowSMS(strPhoneNo, strMessage);
}
});
return rootView;
}
// ---sends a SMS message to another device---
private void BookNowSMS(String phoneNumber, String message) {
/*
* PendingIntent pi = PendingIntent.getActivity(this, 0, new
* Intent(this, test.class), 0); SmsManager sms =
* SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null,
* message, pi, null);
*/
String SENT = "SMS_SENT";
// String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(getActivity(), 0, new Intent(
SENT), 0);
/*
* PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new
* Intent(DELIVERED), 0);
*/
// ---when the SMS has been sent---
getActivity().registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getActivity(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getActivity(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getActivity(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getActivity(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getActivity(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
I forgot the date and time picker arrrrrrrgh
I've added the following 2 classes which have no errors and seem to function fine.
DatePickerFragment.java
PHP:
package com.test.dfw;
import java.util.Calendar;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;
import android.widget.TextView;
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
TextView txtDate;
public DatePickerFragment(TextView txtDate) {
super();
this.txtDate = txtDate;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
txtDate.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
}
}
TimePickerFragment.java
PHP:
package com.test.dfw;
import java.util.Calendar;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TextView;
import android.widget.TimePicker;
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener{
TextView txtTime;
public TimePickerFragment(TextView txtTime) {
super();
this.txtTime = txtTime;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
txtTime.setText(hourOfDay+":"+minute);
}
}
I then updated BookNowFragment.java
PHP:
package com.test.dfw;
import java.util.Calendar;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class BookNowFragment extends Fragment implements OnClickListener {
Button buttonSubmit;
EditText edittextPhone;
EditText editTextProblem;
Button btnChangeDate,btnChangeTime;
TextView txtDisplayDate,txtDisplayTime;
DatePicker datePicker;
TimePicker timePicker;
private int year;
private int month;
private int day;
private int hour;
private int minute;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_booknow,
container, false);
showCurrentDateOnView();
showCurrentTimeOnView();
buttonSubmit = (Button) rootView.findViewById(R.id.buttonSubmit);
// edittextPhone = (EditText) rootView.findViewById(R.id.edittextPhone);
// editTextProblem = (EditText)
// rootView.findViewById(R.id.editTextProblem);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String strPhoneNo = "00000000";
TextView txtName = (TextView) rootView
.findViewById(R.id.edittextName);
TextView txtPhone = (TextView) rootView
.findViewById(R.id.edittextPhone);
//TextView txtDate = (TextView) rootView.findViewById(R.id.date);
TextView txtProblem = (TextView) rootView
.findViewById(R.id.editTextProblem);
String strName = "Name: " + txtName.getText().toString();
String strPhone = "Phone: " + txtPhone.getText().toString();
//String strDate = "Date: " + txtDate.getText().toString();
String strProblem = "Problem: "
+ txtProblem.getText().toString();
String strMessage = strName + "\n" + strPhone + "\n" + strProblem;
BookNowSMS(strPhoneNo, strMessage);
}
});
return rootView;
}
// ---sends a SMS message to another device---
private void BookNowSMS(String phoneNumber, String message) {
/*
* PendingIntent pi = PendingIntent.getActivity(this, 0, new
* Intent(this, test.class), 0); SmsManager sms =
* SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null,
* message, pi, null);
*/
String SENT = "SMS_SENT";
// String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(getActivity(), 0,
new Intent(SENT), 0);
/*
* PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new
* Intent(DELIVERED), 0);
*/
// ---when the SMS has been sent---
getActivity().registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getActivity(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getActivity(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getActivity(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getActivity(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getActivity(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
// display current date
public void showCurrentDateOnView() {
txtDisplayDate = (TextView) findViewById(R.id.txtDate);
datePicker = (DatePicker) findViewById(R.id.datePicker1);
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// set current date into textview
txtDisplayDate.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" "));
// set current date into datepicker
datePicker.init(year, month, day, null);
}
// display current time
public void showCurrentTimeOnView() {
txtDisplayTime = (TextView) findViewById(R.id.txtTime);
timePicker = (TimePicker) findViewById(R.id.timePicker1);
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
// set current time into textview
txtDisplayTime.setText(
new StringBuilder().append(hour)
.append(":").append(minute));
// set current time into timepicker
timePicker.setCurrentHour(hour);
timePicker.setCurrentMinute(minute);
}
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment(txtDisplayDate);
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment(txtDisplayTime);
newFragment.show(getSupportFragmentManager(), "timePicker");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
The problem areas are all under BookNowFragment.java;
1. Under "showCurrentDateOnView" the both findViewById says undefined for the type.I have tried adding rootView but didnt work.
2. Under "showCurrentTimeOnView" both findViewById says undefined for the type.I have tried adding rootView but didnt work.
3. under "showDatePickerDialog" and "showTimePickerDialog" both the getSupportFragmentManager methods show the error "The method getSupportFragmentManager() is undefined for the type BookNowFragment"
4. I also have errors with "onCreateOptionsMenu".I worked out some of them by adding getActivity (see new code below) but it still shows the error "The method onCreateOptionsMenu(Menu) of type BookNowFragment must override or implement a supertype method"
PHP:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getActivity().getMenuInflater().inflate(R.menu.main, menu);
return true;
}
Think there simple issues although I'm simple as well so I could be understating it.

[Q] Code placement for writing TCP/IP data to TextView

Hello,
I am a first time poster new to Android app development so please bear with me. I am currently working off of two great TCP/IP Client examples. My goal is to create a simple TCP/IP Client that connects to a server and, once a connection is established, continuously updates a TextView with strings passed from the server. If the user presses a button, the client sends a stop command to the server and I would ultimately like to expand the TextView into a graph with the converted string values. I am able to establish the connection to the server and send the stop command from the client but my attempts at adding the read capability have, so far, been unsuccessful with the app crashing as soon as it starts up.
Since it is my first time posting, I am not allowed to link the examples I am using. If anyone is interested in seeing them, however, they are posts from the android-er blog titled: "Android Server/Client example - client side using Socket" and "Bi-directional communication between Client and Server, using ServerSocket, Socket, DataInputStream and DataOutputStream".
Here is the code in my MainActivity:
Code:
package com.example.androidclient;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView textResponse;
TextView textIn;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonStopTest, buttonDisconnect;
Socket socket = null;
DataInputStream incomingString = null;
DataOutputStream terminalLetter = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
editTextAddress = (EditText)findViewById(R.id.address);
editTextPort = (EditText)findViewById(R.id.port);
buttonConnect = (Button)findViewById(R.id.connect);
buttonDisconnect = (Button)findViewById(R.id.disconnect);
buttonStopTest = (Button)findViewById(R.id.stop_test);
textResponse = (TextView)findViewById(R.id.response);
textIn = (TextView)findViewById(R.id.text_in);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
buttonStopTest.setOnClickListener(buttonStopTestOnClickListener);
buttonDisconnect.setOnClickListener(buttonDisconnectOnClickListener);
}
OnClickListener buttonConnectOnClickListener = new OnClickListener(){
//setOnClickListener sets a callback to be invoked when the button is clicked
@Override
public void onClick(View arg0) {
//Clicking button (Connect) calls a MyClientTask defined below.
MyClientTask myClientTask = new
MyClientTask(editTextAddress.getText().toString(),
Integer.parseInt(editTextPort.getText().toString()));
myClientTask.execute();
}
};
OnClickListener buttonStopTestOnClickListener = new OnClickListener(){
//setOnClickListener sets a callback to be invoked when the button is clicked
@Override
public void onClick(View arg0) {
try {
terminalLetter = new DataOutputStream(socket.getOutputStream());
terminalLetter.writeByte('b');
terminalLetter.writeByte('\n');
terminalLetter.close();
socket.close();
}
catch (IOException e) {
System.err.println("Couldn't get I/O for the connection.");
}
}
};
OnClickListener buttonDisconnectOnClickListener = new OnClickListener(){
//setOnClickListener sets a callback to be invoked when the button is clicked
@Override
public void onClick(View arg0) {
try {
socket.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String IPaddress;
int Port;
String response = "";
MyClientTask(String addr, int port){
IPaddress = addr;
Port = port;
}
@Override
protected Void doInBackground(Void... arg0) {
//Took socket declaration from here.
try {
//Taking relevant parameters and applying them to socket
socket = new Socket(IPaddress, Port);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
incomingString = new DataInputStream(socket.getInputStream());
textIn.setText(incomingString.readUTF());
/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}
finally{
if(socket != null){
try {
socket.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
I put the commands for reading data from the server and writing it to the TextView with the code that sets up the connection to the socket. The idea was that it would be the next step after the connection is established but I realize that it looks like I am only reading once. I tried adding a while loop and bringing it out of the doInBackground. In each case, all I got was the whole app crashing on me. It looks fairly straight forward in the example but there the connection is automatic, not triggered and I have not been able to modify the code successfully.
I am still new to Android and this feels like it is an important part of app development so I am hoping someone in the community can help me understand where the section of code relevant to reading data (continuously) should be placed in relation to the rest.
Best,
Yusif Nurizade
P.S. I was going to include the fragment but, since the post is long enough, I chose to omit it. I can share upon request and the logcat.

Categories

Resources