Android studio parsing json object - java

i have a issue with my code in android studio. the url of json object is not been open. when i change the url for testing whether there is any problem with my code or not, it is ok. and the only diffrence between those two urls is one of them is https (which run without any problem) and the other is http (which is not working). how can i run the code with out problem?
package com.example.chatbot;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view){
TextView textView = findViewById(R.id.textView);
String input = textView.getText().toString();
//textView.setText(" ");
TextView out=findViewById(R.id.outPut);
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
String url ="http://api.brainshop.ai/get?bid=159114&key=OCfIpglFJbfXDt2G&uid=[uid]&msg=[msg]=hello";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//set the text
String res = response.toString();
Toast.makeText(MainActivity.this,response.toString(),Toast.LENGTH_SHORT).show();
out.setText(res);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(request);
}
}

You should set "android:usesCleartextTraffic" flag to true in your AndroidManifest file.
Since target api 28 it defaults to false. more info here

Related

How to create Quiz app using Volley library

I am creating quiz app from volley library in android. where I get data in Array list from external website. now problem is that how to set data in Textview and Buttons. I created one Textviewfor show question, four Buttions for options, and Two more Buttions for go to next question and go to previous question. here is image
I want that when i click one of the option button than his color will be blue and rest of button will be grey. when i click next button than load new question and all options button will be grey.
here is my main activity.java code. please help me in create quiz app.
package com.ravindra.excelrecycleview;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.ProgressDialog;
import android.os.Bundle;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URL;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private QuestionAdapter mQuestionAdatpter;
private ArrayList<question> mquestion;
private RequestQueue mRequestQueue;
ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recylcer_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mquestion = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON(){
loading = ProgressDialog.show(this,"Loading","please wait",false,true);
String url ="https://script.google.com/macros/s/AKfycbw6eHqtKTxHoS9HPSdfTasY-iebLQXUgS3sHHiOpeuGxJfssBI/exec?action=getQuestions";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("items");
for (int i =0;i<jsonArray.length();i++){
JSONObject items = jsonArray.getJSONObject(i);
String questions = items.getString("questions");
String optiona = items.getString("optiona");
String optionb = items.getString("optionb");
String optionc = items.getString("optionc");
String optiond = items.getString("optiond");
String correctans = items.getString("correctans");
String explain = items.getString("explain");
mquestion.add(new question(questions,optiona,optionb,optionc,optiond,correctans,explain));
}
mQuestionAdatpter = new QuestionAdapter(MainActivity.this,mquestion);
mRecyclerView.setAdapter(mQuestionAdatpter);
loading.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
} );
mRequestQueue.add(request);
int socketTimeOut = 50000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeOut, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
request.setRetryPolicy(policy);
}
}

volley timeout error...Data inserting two times

I m getting volley timeout error every time i try to insert data..Despite of the error, the data is inserted correctly but its inserting two times every time i press the button.
I need to remove the error and insert data only once. Also it takes too much time after clicking button to display error.
package com.example.sumit.myapplication;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.MutableData;
import com.google.firebase.database.Transaction;
import com.google.firebase.database.ValueEventListener;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Sumit on 20-02-2018.
*/
public class register extends Fragment{
RequestQueue requestQueue;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
View v = inflater.inflate(R.layout.login,container,false);
return v;
}
public void onCreate(Bundle savedInstancesState)
{
super.onCreate(savedInstancesState);
TextView t = (TextView) ((MainActivity) getActivity()).findViewById(R.id.textView3);
t.setText("Register");
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
final View vt = super.getView();
final CardView b=(CardView)vt.findViewById(R.id.cardView);
final TextView txt = (TextView)vt.findViewById(R.id.uid);
final EditText txt1 = (EditText) vt.findViewById(R.id.editText);
final EditText txt2 = (EditText) vt.findViewById(R.id.editText2);
final EditText txt3 = (EditText) vt.findViewById(R.id.editText3);
final EditText txt4 = (EditText) vt.findViewById(R.id.editText4);
final Spinner hostel1=(Spinner) vt.findViewById(R.id.spinner1);
final Spinner branch1=(Spinner) vt.findViewById(R.id.spinner2);
final String HttpUrl = "https://testzineapp.000webhostapp.com/insert_record.php";
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View vt) {
final String id=txt1.getText().toString().trim();
final String name=txt2.getText().toString().trim();
final String number=txt3.getText().toString().trim();
final String email=txt4.getText().toString().trim();
final String hostel=hostel1.getSelectedItem().toString().trim();
final String branch=branch1.getSelectedItem().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String ServerResponse) {
// Showing response message coming from server.
Toast.makeText(getContext(), ServerResponse, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
// Showing error message if something goes wrong.
Toast.makeText(getContext(), volleyError.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Creating Map String Params.
Map<String, String> params = new HashMap<String, String>();
// Adding All values to Params.
params.put("College_ID", id);
params.put("Name", name);
params.put("Mobile_Number", number);
params.put("Email_ID", email);
params.put("Hosteller", hostel);
params.put("Branch", branch);
return params;
}
};
// Creating RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);
txt1.setText("");
txt2.setText("");
txt3.setText("");
txt4.setText("");
};
});
super.onViewCreated(view, savedInstanceState);
}
}
Because of volley default retry policy your your request is processing two times, try this code to avoid it.
stringRequest.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(_context);
requestQueue.add(stringRequest);

Unable to load data in Webview or Webview is blank when clicking on listitem

This is my webview actvity:
package com.example.murarilal.volley;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class ArticleActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_article);
WebView webView=(WebView)findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
Intent intent=getIntent();
webView.loadData(intent.getStringExtra("description"),"text/html","UTF-8");
}
}
Mainactivity:
When I click on a listitem then in new activity webview appears blank. Nothing is there in the webview "https://newsapi.org/v1/articles?source=techcrunch&apiKey=59b308aec9f242fe98b527ab9ba93199" this is the URL. The same problem appears when I tested it on real device.
package com.example.murarilal.volley;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
RequestQueue queue;
ListView listView;
List<Hero> heroList;
private String url="https://newsapi.org/v1/articles?source=techcrunch&apiKey=59b308aec9f242fe98b527ab9ba93199";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queue = Volley.newRequestQueue(this);
home();
listView = (ListView) findViewById(R.id.listView);
heroList = new ArrayList<>();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(),ArticleActivity.class);
startActivity(intent);
}
});
}
public void home() {
JsonObjectRequest request =new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject obj = new JSONObject(String.valueOf(response));
JSONArray array = obj.getJSONArray("articles");
for (int i = 0; i < array.length(); i++) {
Hero hero = new Hero((String) array.getJSONObject(i).get("title"), (String) array.getJSONObject(i).get("urlToImage"));
heroList.add(hero);
}
ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(request);
}
}
This is my mainactvity.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.murarilal.volley.MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
/>
</RelativeLayout>
You are fetching data from intent.getStringExtra("description") but you didn't add data into Intent which you want to pass, Try this,
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent=new Intent(getApplicationContext(),ArticleActivity.class);
intent.putExtra("description","whatever data you want to pass");
startActivity(intent);
}
});
And load your URL in below way,
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://www.example.com");
Load an URL in webview:
private String url="https://newsapi.org/v1/articles?source=techcrunch&apiKey=59b308aec9f242fe98b527ab9ba93199";
WebView webView=(WebView)findViewById(R.id.webView);
webView.loadurl(url);
https://developer.android.com/reference/android/webkit/WebView.html#loadUrl(java.lang.String)

Display to another activity json array result from onPostExecute

How do I get the json result from onPostExecute to another activity? I was able to get the user details from the database based on the username logged in. So in my HomePageActivity there is a button to go to profile and when I clicked on btnprofile it displays the user details on textviews in the current activity(HomePageActivity) but what I wanted to do is to get the user details and then display it to a new activity, which is in the Profile Activity. I tried using Intent but when I go to Profile Activity it displays nothing. Can you please help me? :(
Here is my HomePageActivity:
package com.example.androidmp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import android.content.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.view.View;
import android.widget.*;
import com.example.androidmp.User;
import java.util.ArrayList;
import java.util.List;
import com.example.androidmp.User;
import com.example.androidmp.Poem;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
public class HomePageActivity extends Activity {
Button btnfeed, btnprofile;
User u = new User();
String Username,Password,Fullname,Email,Location,Bio,uname;
String getusername,getpw,getfn,getem,getloc,getb;
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
HashMap<String, String> hashMap = new HashMap<String, String>();
Intent i;
Bundle bundle;
private static final String USERNAME = "Username";
private static final String PASSWORD = "Password";
private static final String FULLNAME = "Fullname";
private static final String EMAIL = "Email";
private static final String BIO = "Bio";
private static final String LOCATION = "Location";
String s="";
TextView fn,em,loc,b;
private static final String TAG_PROFILE = "user";
private static final String PROFILE_URL = "http://192.168.1.5/webservices/mycontroller/getUser.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
Intent intent = getIntent();
u.SetUsername(intent.getStringExtra(u.username()));
fn = (TextView) findViewById(R.id.textView1);
em = (TextView) findViewById(R.id.textView2);
loc = (TextView) findViewById(R.id.textView3);
b = (TextView) findViewById(R.id.textView4);
TextView textView = (TextView) findViewById(R.id.getusername);
textView.setText(u.getUsername());
uname = u.getUsername().toString();
//uname = textView.toString();
//u.SetUsername(uname.toString());
btnprofile = (Button) findViewById(R.id.btnprofile);
btnfeed = (Button) findViewById(R.id.btnfeed);
//getem = em.getText().toString();
//getloc = loc.getText().toString();
//getb = b.getText().toString();
btnprofile.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new ProfileAsync().execute();
Intent i = new Intent(HomePageActivity.this,ProfileActivity.class);
i.putExtra("fullname",Fullname);
i.putExtra("email", Email);
i.putExtra("bio", Bio);
i.putExtra("location", Location);
startActivity(i);
finish();
}
});
btnfeed.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent a = new Intent(HomePageActivity.this,FeedActivity.class);
startActivity(a);
}
});
}
class ProfileAsync extends AsyncTask<String, String, String>{
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(HomePageActivity.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
String json=null;
byte[] data;
StringBuffer buffer = null;
InputStream is = null;
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Username", uname));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(PROFILE_URL);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
json = EntityUtils.toString(entity);
Log.e("Profile JSON: ", json.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPostExecute(String json){
super.onPostExecute(json);
loadingDialog.dismiss();
try
{
jsonobject = new JSONObject(json);
jsonarray = jsonobject.getJSONArray("user");
JSONObject jb= jsonarray.getJSONObject(0);
//Username = jb.getString("Username");
//Password = jb.getString("Password");
Fullname = jb.getString("Fullname");
Email = jb.getString("Email");
Bio = jb.getString("Bio");
Location = jb.getString("Location");
fn.setText(Fullname);
em.setText(Email);
loc.setText(Location);
b.setText(Bio);
}catch(Exception e)
{
e.printStackTrace();
}
}
}//end of asynctask
}
Here is my ProfileActivity:
package com.example.androidmp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import android.content.*;
import com.example.androidmp.User;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.view.View;
import android.widget.*;
public class ProfileActivity extends Activity {
Button btncreate;
private TextView _username,_password,_fullname,_Email,_bio,_location;
User u = new User();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profileview);
//_username = (TextView) findViewById(R.id._username);
//_password = (TextView) findViewById(R.id._password);
_fullname = (TextView) findViewById(R.id._fullname);
_Email = (TextView) findViewById(R.id._Email);
_bio = (TextView) findViewById(R.id._bio);
_location = (TextView) findViewById(R.id._location);
Intent i = getIntent();
u.SetUsername(i.getStringExtra(u.username()));
_username.setText(u.getUsername());
String displayfullname = i.getExtras().getString("fullname");
String displayemail = i.getExtras().getString("email");
String displaybio = i.getExtras().getString("bio");
String displaylocation = i.getExtras().getString("location");
_fullname.setText(displayfullname);
_Email.setText(displayemail);
_bio.setText(displaybio);
_location.setText(displaylocation);
}
}
It is because new activity starts before async task is completed. Just call function for start new activity in onPostExecute() function.
Pass values after fetching the details. Is the settext working properly? then you can give the intent at that scope, in the onPostexecute method. Look before doing this.Look this

onPostExecute gets called too late

First I will describe the process/problem briefly in words. Afterwards, I'll attach all of the code.
I start the android application in debug mode.
Main activity gets called.
It calls Activity2 via "intent".
Then (in onCreate) I start an Async activity in order to get information from a webserver. I do that with this command "new Kontakt(info1, info2, information).execute();"
I've put a break point at the onPostExecute method in "Kontakt" to see what happens. But!! It doesn't stop there. So then I figured, "okey, the doInBackground method didn't get called for some reason"
When I continue to run the code, as a surprise, onPostExecute gets called (somewhere at the end of onClick) and stops at the break point just the way I want it but than it's too late, because I'd like to have the output already in the onCreate method where I called "new Kontakt(info1, info2, information).execute();".
So why does it call onPostExecute too late and what can I do to make the process call it properly already in onCreate at the line "new Kontakt(info1, info2, information).execute();" in Activity2?
The code is below
MainActivity.java
package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
Intent intent = new Intent(this, Activity2.class);
startActivity(intent);
break;
}
}
}
Activity2.java
package com.example.myapplication;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
public class Activty2 extends ActionBarActivity implements View.OnClickListener {
Button button;
Context information;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
information=this;
String info1="Yeah";
String info2="Yeah";
new Kontakt(info1, info2, information).execute();
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.button) {
}
}
Kontakt.java
package com.example.myapplication;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;
import java.util.ArrayList;
public class Kontakt extends AsyncTask<Void, Void, Integer> {
public static final int CONNECTION_TIMEOUT = 1000 * 15;
public static final String SERVER_ADDRESS = "http://test.site.net/";
String info1;
String info2;
private final Context information;
public Kontakt(String info1, String info2, Context context) {
this.info1=info1;
this.Info2=info2;
this.information=context;
}
#Override
protected Integer doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("user", info1));
dataToSend.add(new BasicNameValuePair("password", info2));
HttpParams httpRequestParams = getHttpRequestParams();
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS
+ "Register.php");
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
int result=1;
return result;
} catch (Exception e) {
e.printStackTrace();
int result=0;
return result;
}
//return null;
}
private HttpParams getHttpRequestParams() {
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams,
CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams,
CONNECTION_TIMEOUT);
return httpRequestParams;
}
#Override
protected void onPostExecute(Integer result)
{
super.onPostExecute(result);
SharedPreferences.Editor editor = information.getSharedPreferences("INTERNET_KOLL", Context.MODE_PRIVATE).edit();
editor.putString("internet_status", String.valueOf(result));
editor.commit();
}
}
In Activity2, when onCreate() calls new Kontakt(info1, info2, information).execute();:
an asynchronous task (Kontakt) is started in the background
the execution of onCreate() continues
so it's normal that you don't have the response immediately.

Categories