as the tittle indicates just want to get data from my php file & check whether entered email , password are of a registered user . If yes then redirect to Success page(TimelineActivity)
Hence had look on this :- How to get values from mysql database using php script in android
This my LoginBasicActivity.java
public class LoginBasicActivity extends AppCompatActivity {
public AutoCompleteTextView uemail;
public EditText upassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_basic);
uemail = (AutoCompleteTextView) findViewById(R.id.emailBasic);
upassword = (EditText) findViewById(R.id.passwordBasic) ;
Button buttonLog = (Button) findViewById(R.id.buttonLog);
buttonLog.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String tem;
String email = uemail.getText().toString();
String result = null;
String password = upassword.getText().toString() ;
// HttpClientBuilder.create();
// As HttpClient client = new DefaultHttpClient(); is not used anymore
HttpClient client = HttpClients.createDefault();
tem = "http://www.example_domain.com/app_folder/verify-user.php?username="+email+"&password="+password;
HttpGet request = new HttpGet(tem);
try {
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
result = reader.readLine();
} catch (Exception e) {
e.printStackTrace();
}
if (result.equals("0") == true) {
Toast.makeText(getApplicationContext(), "Sorry try again", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Welcome Client", Toast.LENGTH_LONG).show();
Intent myIntt = new Intent(view.getContext(), TimelineActivity.class);
startActivityForResult(myIntt, 0);
}
}
});
}
}
This is verify-user.php
<?php
mysql_connect("localhost","user_name","user_password") or die(mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$username=$_REQUEST['username'];
$password=$_REQUEST['password'];
$SelectQuery="select * from table_name where C_Username='$username' and C_Password='$password'";
$result=mysql_query($SelectQuery) or die(mysql_error());
$count=mysql_num_rows($result);
$row=mysql_fetch_array($result);
if($count==0)
echo "0";
else
echo $row['c_id'];
?>
After this i got some file duplication issue in build.gradle , so added this in build.gradle
android {
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/LICENSE'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/NOTICE'
}
}`
Now , when Login button is pressed dialogbox says "Unfourtunately app_name has stopped "
Logcat :- https://www.dropbox.com/s/63cv806z4y8h9my/2015-11-10-05-01-44%5B1%5D.txt?dl=0
Im little bit new to Android-Java.
How to fix this issue ? Can someone explain correct syntax , where its going wrong ?
You are making the network(api) request over main thread which is causing problem.Make the api hit from a thread or use the AsyncTask or Loader for it.
Also check if you have added internet permission to your manifest file or not.if not than add the following line in your manifest file.
<uses-permission android:name="android.permission.INTERNET"/>
Edit: You can make a inner class like as follows in your activity and call it on button click using new LoginAsyncTask().execute();
public class LoginAsyncTask extends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... params) {
//Run in background thread(can not access UI and not able to perform UI related operations here).
//make your network hit here and return the result which is string in your case.
//The onPostExecute Method is get called automatically after this method returns.
...
}
protected void onPreExecute() {
//run on main thread(can access UI)
//do some initialization here,if needed, before network hit.
...
}
protected void onPostExecute(String result) {
//Method run on main thread,can access UI.result is the value returned by doInBackground method.
//Put a check over result and perform the further operation accordingly.
.....
}
}
Related
I try to add data from my object to ArrayList but it's not work.
This code read data from JSON and add to ArrayList in MySQLConnect.java like this.
private ComputerService computerservice;
public static ArrayList<ComputerService> computerServicesArrayList = new ArrayList<>();
private String URL = "http://10.200.100.10/", GET_URL = "android/get_data.php";
public MySQLConnect(){
main = null;
}
public MySQLConnect(Activity mainA){
main = mainA;
}
public List<ComputerService> getData(){
String url = URL + GET_URL;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(main, error.getMessage().toString(), LENGTH_LONG).show();
}
}
);
RequestQueue requestQueue = Volley.newRequestQueue(main.getApplicationContext());
requestQueue.add(stringRequest);
return computerServicesArrayList;
}
public void showJSON(String response){
String data_mysql = "";
computerServicesArrayList.clear();
try{
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray("data");
for(int i=0; i < result.length(); i++){
JSONObject collectData = result.getJSONObject(i);
String id = collectData.getString("id");
String type = collectData.getString("type");
String address = collectData.getString("address");
computerservice = new ComputerService(id, type, address);
computerServicesArrayList.add(computerservice);
}
System.out.println("Size in class MySQLConnect");
System.out.println(computerServicesArrayList.size());
} catch (JSONException e) {
e.printStackTrace();
}
}
The MainActivity.java I show computerServicesArrayList.size() like this.
public static List<ComputerService> computerServicesArrayList;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySQLConnect = new MySQLConnect(MainActivity.this);
update();
}
public void update(){
computerServicesArrayList = mySQLConnect.getData();
System.out.println("Size in MainActivity");
System.out.println(computerServicesArrayList.size());
}
The output show like this.
Size in MainActivity
0
Size in class MySQLConnect
83
From the code I can print computerServicesArrayList.size() the result is 83 but when I print from MainActivity why it show result 0. How to fix it?
I don't know the Volley framework/classes in detail. But it looks like you are creating an asynchronous request. So your rest-request gets send and when the response comes in your showJSON() method is called.
But you immediatley return the computerServicesArrayList result, which is empty because you don't have your response yet. This is also the reason why the print statement from your MainActivity is executed before the print from your showJSON method.
If you want to wait for the rest-response you have to do synchronous requests.
Maybe this can help you more about Volley and asyn/sync requests:
how to wait the volley response to finish it's work inside intentservice?
Can I do a synchronous request with volley?
But normally you would send an async-request and when you get the response you do your logic (update fields, store something in database, ...).
Your computerServicesArrayList is populated by callback from Volley (new Response.Listener()). This population happens correctly as you have verified. But it does take some time, for the network up/down travel. When your MainActivity's call to mySQLConnect.getData() returns this round trip is not complete yet; so you get an empty list in MainActivity.
The usual solution to this problem is to make the listener call methods in MainActivity. This can be done by making
class MainActivity implements Response.Listener<String> {
/* --- */
#Override
public void onResponse(String response) {
showJSON(response);
}
void showJSON(String response){
// Do the stuff here
}
So I'm really new in android, and going to make an application which get the device id of a device, store it on database server, and then check it if the device are the same with the one already registered, if yes, then go to main activity, if not then they need to registered again.
My method :
public class SigninActivity extends AsyncTask<String, String, String> {
private Context context;
public SigninActivity(Context context, int flag) {
this.context = context;
}
protected void onPreExecute(String result) {
}
//#Override
protected String doInBackground(String... arg0) {
try {
String dev = (String) arg0[0];
String link = "http://10.20.2.14/service_antrian/get_data.php?device_id=" + dev;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
Log.d("RETURN", "return");
return sb.toString();
} catch (Exception e) {
Log.d("EXCEPTION", "EXP");
//return "failed";
return new String("Exception: " + e.getMessage());
}
}
// #Override
protected void onPostExecute(String result) {
if (result.equalsIgnoreCase("false")) {
Intent mainIntent = new Intent(UserActivity.this, RegisterActivity.class);
UserActivity.this.startActivity(mainIntent);
} else {
Intent mainIntent = new Intent(UserActivity.this, MainActivity.class);
UserActivity.this.startActivity(mainIntent);
}
}
}
and this is my service in php code:
<?php
ini_set('display_errors', 1);
require_once 'database.php';
if(isset($_GET['device_id'])) {
$device_id = $_GET['device_id'];
$sql = " SELECT * FROM `pasien`.`antrian_mobile` WHERE `device_id`=
'$device_id' ";
$rs = $mysqli->query($sql);
$data = array();
while ($row = $rs->fetch_object()) {
$data[] = $row;
}
if ($mysqli->affected_rows > 0) {
echo "successfull";
} else {
echo "false";
}
echo json_encode($data);
}
?>
but that code only make the app go to the main activity, while there are no records on the database yet. Is it because of my service?
You are returning successfull or failed from your service
if ($mysqli->affected_rows > 0) {
echo "successfull";
} else {
echo "failed";
}
but you are comparing the result with false in your mobile app, hence it always takes the else route and open MainActivity
if (result.equalsIgnoreCase("false")) {
Intent mainIntent = new Intent(UserActivity.this, RegisterActivity.class);
UserActivity.this.startActivity(mainIntent);
} else {
Intent mainIntent = new Intent(UserActivity.this, MainActivity.class);
UserActivity.this.startActivity(mainIntent);
}
I see a few issues in your code:
issue #1
Activity shouldn't extend AsyncTask. AsyncTask should be dedicated to a single asynchronous task (like sending HTTP request) and Activity is representing single user screen (UI layer). You should create AsyncTask separately and call it within an Activity like this:
class SigninActivity extends Activity {
// this method should be called in the place where you want to execute your task
// it could be onResume() method, onClick listener for the button or whatever
private void executeAsyncTask() {
new MyTask().execute(...) // put your params here...
}
private class MyTask extends AsyncTask<String, String, String> {
... // your task code goes here...
}
}
issue #2
Nowadays, using AsyncTask is considered as a bad practice in Android applications, because it has poor error handling and is not aware of the Activity lifecycle. Recommended solution for asynchronous operations on Android is RxJava (version 2).
issue #3
You are using HttpClient. It's recommended to use more mature solutions like Retrofit Http REST client or OkHttp library. They can be easily integrated with RxJava.
issue #4
You're passing Context, but you're not using it
issue #5
You don't have to comment #Override annotations.
issue #6
Your code is messy, hard to debug and read. Once you make it clean, it will be easier to solve problems related to it.
issue #7
In the PHP code, you're mixing responsibilities.
Summary
Make sure you're using the existing code correctly and then try to improve it.
I am working on developer authenticated project.And I am trying to get credentials using this below code.But it is giving me following error.
I have pasted IdentityId and Token manually into this code from server code:
Caused by: com.amazonaws.services.cognitoidentity.model.ResourceNotFoundException: Identity 'ap-northeast-1:fe81cd76-e9d4-4416-99ea-b684b78743c8' not found. (Service: AmazonCognitoIdentity; Status Code: 400; Error Code: ResourceNotFoundException; Request ID: 2ac65fe8-d41a-11e5-8674-677eefdb5331)
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:709)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:385)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:196)
at com.amazonaws.services.cognitoidentity.AmazonCognitoIdentityClient.invoke(AmazonCognitoIdentityClient.java:533)
at com.amazonaws.services.cognitoidentity.AmazonCognitoIdentityClient.getCredentialsForIdentity(AmazonCognitoIdentityClient.java:406)
at com.example.sandesh.aws.MainActivity$network.doInBackground(MainActivity.java:101)
at com.example.sandesh.aws.MainActivity$network.doInBackground(MainActivity.java:52)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
Here is my code: MainActivity.java
public class MainActivity extends AppCompatActivity {
Button button;
protected static CognitoCachingCredentialsProvider credentialsProvider = null;
private GetCredentialsForIdentityResult credentialsForIdentityResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
network net = new network();
net.execute();
}
});
}
public class network extends AsyncTask<Void,Void,String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
Authentication developerProvider = new Authentication(
null,
"ap-northeast-1:XXXXXXXXXXXXXXXXXX",
Regions.AP_NORTHEAST_1);
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
getApplicationContext(),
developerProvider,
Regions.AP_NORTHEAST_1);
HashMap<String, String> loginsMap = new HashMap<String, String>();
loginsMap.put(developerProvider.getProviderName(), "7386372772");
credentialsProvider.setLogins(loginsMap);
credentialsProvider.refresh();
GetCredentialsForIdentityRequest credentialsForIdentityRequest = new GetCredentialsForIdentityRequest();
credentialsForIdentityRequest.setIdentityId(developerProvider.getIdentityId());
credentialsForIdentityRequest.setLogins(loginsMap);
AmazonCognitoIdentityClient cognitoIdentityClient = new AmazonCognitoIdentityClient(credentialsProvider);
credentialsForIdentityResult = cognitoIdentityClient.getCredentialsForIdentity(credentialsForIdentityRequest);
Log.d("access_key",credentialsForIdentityResult.getCredentials().getAccessKeyId());
return credentialsForIdentityResult.getCredentials().getAccessKeyId();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}}
Authentication.java
public class Authentication extends AWSAbstractCognitoDeveloperIdentityProvider {
private static final String PROVIDERNAME = "login.blupinch.app";
public String response = " ";
String line = " ";
public Authentication(String accountId, String identityPoolId, Regions region) {
super(accountId, identityPoolId, region);
}
#Override
public String getProviderName() {
return PROVIDERNAME;
}
public String refresh() {
setToken(null);
if (getProviderName() != null &&
!this.loginsMap.isEmpty() &&
this.loginsMap.containsKey(getProviderName())) {
update(identityId, token);
return "eyJraWQiOiJhcC1ub3J0aGVhc3QtMTEiLCJ0eXAiOiJKV1MiLCJhbGciOiJSUzUxMiJ9.eyJzdWIiOiJhcC1ub3J0aGVhc3QtMTpmZTgxY2Q3Ni1lOWQ0LTQ0MTYtOTllYS1iNjg0Yjc4NzQzYzgiLCJhdWQiOiJhcC1ub3J0aGVhc3QtMTphODcxZmE1Zi0yM2EyLTQ4MGQtYmFhNi1iNGVkMzE0MzcyNDQilCJhbXIiOlsiYXV0aGVudGljYXRlZCIsImxvZ2luLmJsdXBpbmNoLmFwcCIsImxvZ2luLmJsdXBpbmNoLmFwcDphcC1ub3J0aGVhc3QtMTphODcxZmE1Zi0yM2EyLTQ4MGQtYmFhNi1iNGVkMzE0MzcyNDQ6NzM4NjM3Mjg3MiJdLCJpc3MiOiJodHRwczovL2NvZ25pdG8taWRlbnRpdHkuYW1hem9uYXdzLmNvbSIsImV4cCI6MTQ1NTU5NTM5NywiaWF0IjoxNDU1NTU5Mzk3fQ.fHHH6aeCn5EaJGxGD6tw7bWyQpPHuYcW8SZLRGVn-3cbamJrWEPmUnNvcLJ-D6nL8AvMQy7-s1LGQ5MNaiuIH7QF6W8aWt2OMALmA_Y7eqpGQ6iQXVma_jTZSpiyBe2cPNggWgeslPtFxomwE90vW0rzS1sY3D5Y3UbnrIHNdiPKIzzP9JaQo1IsTJMKEpQM-jzWP6stV1radDuIzWQroBVQseOQSD-MXV_-cgWWSx0eQmtFbjJW6RP_nACgh0uTbGmMuOi2iKXKQAdGlYWO-PHlShbiHT-WLQoZNWuh95Hh9dMldv-mNdnYSblqYyqptLA3kObioI08XXkTqwaaAw";
} else {
this.getIdentityId();
return null;
}
}
public String getIdentityId() {
identityId = "ap-northeast-1:XXXXXXXXXXXXXXXXXXXXXXXX";
if (identityId == null) {
if (getProviderName() != null && !this.loginsMap.isEmpty()
&& this.loginsMap.containsKey(getProviderName())) {
update(identityId, token);
return "ap-northeast-1:XXXXXXXXXXXXXXXXXXXX";
} else {
return super.getIdentityId();
}
} else {
return identityId;
}
}}
I have tried it in PHP where I performed getOpenIdTokenForDeveloperIdentity , stsClient and AssumerolewithWebIdentity to get credentials it worked great. Thank you in advance.
When using Developer Authenticated Identities, the logins map for the call GetCredentialsForIdentity should have "cognito-identity.amazonaws.com" as the key instead of developer provider name.
Also, you should not be calling this method yourself, the SDK will take care of this.
Update:
When calling getCredentialsForIdentity, in the logins map, when key is "cognito-identity.amazonaws.com", the value should be the token you got from your backend after calling GetOpenIdTokenForDeveloperIdentity. You do not need to get the credentials for doing AWS operations, just initialize the AWS Service Client with this credentials provider and you should be good to go.
(1) In your application, you do not need to call GetCredentialsForIdentity, the CredentialsProvider does all of this for you. (And ensures the correct arguments are passed in).
--> You can test that you are getting credentials by making a call to another service that requires credentials (ex S3)
--> Another option is to call getCredentials() on the Credentials Provider and validate that an exception is not thrown
(2) In Authentication.java, refresh, you seem to be using a hard coded token? This is likely expired, and you should make sure to get new ones. (If you are just testing app side, make sure you hard code a fresh one).
(3) In Authentication.java, refresh, it looks like you are calling update with a null token.
(4) Also make sure you are getting tokens for the hard coded identity you are using. (Again, you should only be hard coding this if you are testing).
I have an activity that when started makes a call to a "json" for get data categories of songs, after that I make a call to the method "AsyncTask" for the list of songs that category from another "JSON "the problem is that when I start the activity, this is locked , after 2 seconds, the activity opens the layout and I can see the categories on the action bar and not because the songs are looking for in the background.
main activity (onCreate):
java.io.InputStream source = null;
source = retrieveStream(UrlApi.URL_BASE + UrlApi.URL_STORE + _bundle.getString("_id") + UrlApi.CATEGORY_SONG);
Log.i("URL - KARAOKE", UrlApi.URL_BASE + UrlApi.URL_STORE + _bundle.getString("_id") + UrlApi.CATEGORY_SONG);
Reader reader = new InputStreamReader(source);
Type happyCollection = new TypeToken<Collection<String>>() {}.getType();
_karaoke_category_response = new Gson().fromJson(reader, happyCollection);
if(_karaoke_category_response.size() < 1){
finish();
Toast.makeText(getApplicationContext(), "Local sin karaokes", Toast.LENGTH_SHORT).show();
}else{
Log.i("Category - response", _karaoke_category_response.toString());
_karaoke_category_adapter = new ArrayAdapter<String>(getSupportActionBar().getThemedContext(), R.layout.spinner_item,_karaoke_category_response);
getSupportActionBar().setListNavigationCallbacks(_karaoke_category_adapter, this);
}
The follow code is of search the songs of that categori and set it
class AsyncKaraoke extends AsyncTask<Void, Void, Void> {
String category;
public AsyncKaraoke(String category) {
this.category = category;
}
protected void onPreExecute(){
super.onPreExecute();
setSupportProgressBarIndeterminateVisibility(true);
}
#Override
protected Void doInBackground(Void... params) {
java.io.InputStream source = null;
try {
source = retrieveStream(UrlApi.URL_BASE + UrlApi.URL_STORE + _bundle.getString("_id") + UrlApi.KARAOKE_URL + UrlApi.FILTER_CATEGORY + URLEncoder.encode(category, "UTF-8"));
Log.i("URL - KARAOKE", UrlApi.URL_BASE + UrlApi.URL_STORE + _bundle.getString("_id") + UrlApi.KARAOKE_URL + UrlApi.FILTER_CATEGORY + URLEncoder.encode(category, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Reader reader = new InputStreamReader(source);
Type karaokeCollection = new TypeToken<Collection<KaraokeModel>>() {}.getType();
_response = new Gson().fromJson(reader, karaokeCollection);
Log.i("Response - KaraokeCategory" , _karaoke_category_response.toString());
return null;
}
protected void onPostExecute(Void Void){
super.onPostExecute(Void);
setSupportProgressBarIndeterminateVisibility(false);
_karaoke_adapter = new KaraokeAdapter(KaraokeActivity.this, _bundle.getString("_id"), _response);
if(_response.size() == 0){
Toast.makeText(getApplicationContext(), "Categoria sin karaoke", Toast.LENGTH_SHORT).show();
}
_list_view.setAdapter(_karaoke_adapter);
_karaoke_adapter.notifyDataSetChanged();
}
}
How should I do to call 2 times to "AsyncTask" method and prevent the activity is engaged by a few seconds?
The primary rule of AsyncTask is that it must always be create and run on the main thread. You will get an exception if you start another AsyncTask inside the doInBackground() method. Your options are to start the next AsyncTask in one of the callbacks. Generally, some people will chain AsyncTask in the onPostExecute() method, but you can also start them in onPreExecute() and onProgressUpdate().
EDIT:
Additionally, you can run AsyncTask in sequence of each other using AsyncTask#executeOnExecutor(). From HoneyComb on, you don't need to do this. All AsyncTask run in a serial thread pool in the order they are executed. Though it may be easier to understand that the code is running serially if you use it. You do need to chain if using Android Android 1.6 - 2.3.x though.
You should build the URL in the main activity, then run an AsyncTask to download the content and finally process the result back in your activity.
The syntax to run an AsyncTask is:
String category = "...";
new AsyncKaraoke().execute(category);
You can also remove the onPostExecute() method from your AsyncKaraoke class and put it in the activity:
String category = "...";
new AsyncKaraoke() {
#Override
protected void onPostExecute(Void Void){
// do stuff (and moving the third type of the AsyncKaraoke to something else
// than Void will allow you to get the result here.
}.execute(category);
Generally, we use AsyncTask to perform an action in another thread than the UI thread to prevent the user from being halt while performing some actions. SO, it does not make any sense to create an additional AsyncTask inside the outer one. Try to manage your code to do it all the those method soInBackground(), onPreExecution() and onPostExecution() and make use of their order of execution
int count = 0;
protected void onPostExecute(Void Void){
super.onPostExecute(Void);
// call same asynctask
if (count == 0)
{
execute asynctask
count++;
}
}
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
whoaa
i really need help, why my code result like that?
this is my code :
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
try{
HttpResponse response = httpClient.execute(httpPost);
String jsonResult = convertStreamToString((response.getEntity().getContent())).toString();
JSONObject obj = (JSONObject) new JSONTokener(jsonResult).nextValue();
JSONObject obj2 = obj.getJSONObject("GetRingkasObjekPajak_SingleResult");
String nameWP = obj2.getString("NM_WP");
TextView tv = (TextView)findViewById(R.id.dummy_text_three);
tv.setText(jsonResult);
}catch (MalformedURLException e) {
// URL is invalid
TextView tv = (TextView) findViewById(R.id.dummy_text_three);
tv.setText("url invalid");
} catch (SocketTimeoutException e) {
// data retrieval or connection timed out
TextView tv = (TextView) findViewById(R.id.dummy_text_three);
tv.setText("RTO");
} catch (IOException e) {
// could not read response body
// (could not create input stream)
TextView tv = (TextView) findViewById(R.id.dummy_text_three);
tv.setText("couldnt read response");
} catch (JSONException e) {
// response body is no valid JSON string
TextView tv = (TextView) findViewById(R.id.dummy_text_three);
tv.setText("json response fail");
}catch (Exception e) {
// TODO: handle exception
TextView tv = (TextView) findViewById(R.id.dummy_text_three);
tv.setText(e.toString());
}
i also have added internet permission
please help me
how to improve my code, so this problem solved.
Here is an example of Async task... Hope it will be helpfull to you.
private class YourAsyncTaskClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//your http network call here.
return null;
}
#Override
protected void onPostExecute(String result) {
//update your ui here
}
#Override
protected void onPreExecute() {
//do any code before exec
}
#Override
protected void onProgressUpdate(Void... values) {
//If you want to update a progress bar ..do it here
}
}
Finally call this class from anywhere you want like..
new YourAsyncTaskClass().execute();
you can not perform network operations from main UI thread. you need to do networking related tasks in different thread. Better use AsyncTask
According to the doc
The exception that is thrown when an application attempts to perform a
networking operation on its main thread.
This is only thrown for applications targeting the Honeycomb SDK or
higher. Applications targeting earlier SDK versions are allowed to do
networking on their main event loop threads, but it's heavily
discouraged.
NetworkOnMainThreadException: The exception that is thrown when an application attempts to perform a networking operation on its main thread.
There is an article about Painless Threading on the Android developer site which is a good introduction to this, and will provide you with much better depth of answer than can be realistically provided here.
Run your code in AsyncTask.
You can learn about asyncTask here is best explanation with good example .
call your webservice inside aynctask.
private class NetworkTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// call your network operation here
}
}