I am trying to insert inputs to database but whenever I try, it adds empty rows to it. I have created an html form that works perfectly. Here is my code I would appreciate any help.
MyFragment.java
public class MyFragment extends Fragment{
EditText senderEt, headerEt, textEt;
Button btn;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.my_fragment, container, false);
senderEt = (EditText)rootView.findViewById(R.id.sender);
headerEt = (EditText)rootView.findViewById(R.id.header);
textEt = (EditText)rootView.findViewById(R.id.text);
btn = (Button) rootView.findViewById(R.id.btnSend);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addToDB(getView());
}
});
return rootView;
}
public void addToDB(View view){
String sender= senderEt.getText().toString();
String header= headerEt.getText().toString();
String text= textEt.getText().toString();
BackgroundTask backgroundTask = new BackgroundTask(getActivity());
backgroundTask.execute(sender, header, text);
}
}
BackgroundTask.java
public class BackgroundTask extends AsyncTask<String, Void, String> {
Context context;
BackgroundTask(Context context){
this.context=context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String add_url= "http://139.179.196.153:8080/addDB.php";
String sender = params[0];
String header = params[1];
String text = params[2];
try {
URL url = new URL(add_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode("sender", "UTF-8") + " = "+URLEncoder.encode(sender, "UTF-8")+"&"+
URLEncoder.encode("header", "UTF-8") + " = "+URLEncoder.encode(header, "UTF-8")+"&"+
URLEncoder.encode("text", "UTF-8") + " = "+URLEncoder.encode(text, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inpInputStream = httpURLConnection.getInputStream();
inpInputStream.close();
return "Add to DB Success";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String res) {
Toast.makeText(context, res, Toast.LENGTH_SHORT).show();
}
}
After I debugged, I got "data" variable in "BackgroundTask" as
sender = fggff&header = kkkjjj&text = qwwqwq
do they have to be in quotes? or are the blanks problem?
php code
<?php
$db_name = "test";
$db_user = "root";
$db_password = "";
$db_server_name = "localhost";
$con = new mysqli($db_server_name, $db_user, $db_password, $db_name);
if($con->connect_error){
echo "Connection error".mysqli_connect_error();
}
else{
echo "<h3>Database connection success</h3>";
}
$sender = $_POST["sender"];
$header = $_POST["header"];
$text = $_POST["text"];
$sql_query = "insert into things values('$sender','$header','$text')";
if(mysqli_query($con, $sql_query)){
echo "<h3>Data insertion success</h3>";
}
else{
echo "<Data insertion error</h3>".mysqli_error($con);
}
Keep in mind that your background task will not do the inserts immediately when called. I think you are passing reference parameters (that is not scalars) and so the caller could be changing them before the background task has a chance to use them.
Two choices: don't do in background - for a local db, a single insert is really fast and can usually be done on the UI thread.
Or, make copies of the strings before you send them to the background task.
Related
So I have been trying to fetch JSON objects in my Django REST Framework API. The algorithm for this called within the onPostExecute of my AsyncTask but it seems that it is not being called as when I debug it doesn't go there. Nothing fatal seems to be appearing in my logcat except that there is nothing in my array that should contain data from the DRF API.
I have two activities that calls my AsyncTask from my WSAdapter class. One is for logging in and the other is for listing all posts once logged in.
The logging in works just fine but listing the posts doesn't.
My code is below:
Posts.java
public class Posts extends AppCompatActivity {
TextView postsSect;
Button postsDoneBtn;
WSAdapter.SendAPIRequests PostsHelper;
StringBuilder postsBuffer = new StringBuilder();
#Override
protected void onResume(){
super.onResume();
PostsDetails postDetailsHelper = new PostsDetails();
postDetailsHelper.ListPosts();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
PostsDetails postDetailsHelper = new PostsDetails();
postsDoneBtn = (Button) findViewById(R.id.PostsDoneButton);
postDetailsHelper.callPostDetails("192.168.0.18:8000/api");
postDetailsHelper.ListPosts();
postDetailsHelper.postDetailsCalled('n');
postsDoneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Posts.this, MainActivity.class));
}
});
}
public class PostsDetails {
//String post_title, post_content;
ArrayList<Integer> post_id = new ArrayList<Integer>();
ArrayList<String> post_title = new ArrayList<String>();
ArrayList<String> post_content = new ArrayList<String>();
boolean isPDCalled;
// sets if Post details are called
boolean postDetailsCalled(char called) {
if (called == 'y'){
return true;
}
return false;
}
// checks if postsDetails functions are called for AsyncTask
boolean getIsPDCalled(){
return isPDCalled;
}
// calls the execute for AsyncTask
private void callPostDetails(String theurl){
PostsHelper = new WSAdapter.SendAPIRequests();
// sets if post details are called
postDetailsCalled('y');
// executes AsyncTask
PostsHelper.execute(theurl);
}
// sets values for the posts arrays
public void setPost(int p_id, String p_title, String p_content) {
post_id.add(p_id);
post_title.add(p_title);
post_content.add(p_content);
}
// Lists the posts from the database
public void ListPosts() {
/////////// add functionality if a post was deleted and was clicked
postsSect = (TextView) findViewById(R.id.PostsSection);
postsSect.setText(post_title.get(post_title.size()) + "\n");
for (int i = post_id.size() - 1; i > 0; i--)
{
postsSect.append(post_title.get(i));
}
}
}
}
WSAdapter.java
public class WSAdapter extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
static public class SendAPIRequests extends AsyncTask<String, String, String> {
// Add a pre-execute thing
#Override
protected String doInBackground(String... params) {
Log.e("TAG", params[0]);
Log.e("TAG", params[1]);
String data = "";
HttpURLConnection httpURLConnection = null;
try {
// Sets up connection to the URL (params[0] from .execute in "login")
httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection();
// Sets the request method for the URL
httpURLConnection.setRequestMethod("POST");
// Tells the URL that I am sending a POST request body
httpURLConnection.setDoOutput(true);
// To write primitive Java data types to an output stream in a portable way
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
// Writes out a byte to the underlying output stream of the data posted from .execute function
wr.writeBytes("postData=" + params[1]);
// Flushes the postData to the output stream
wr.flush();
wr.close();
// Representing the input stream
InputStream in = httpURLConnection.getInputStream();
// Preparing input stream bytes to be decoded to charset
InputStreamReader inputStreamReader = new InputStreamReader(in);
StringBuilder dataBuffer = new StringBuilder();
// Translates input stream bytes to charset
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
// concatenates data characters from input stream
dataBuffer.append(current);
}
data = dataBuffer.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
// Disconnects socket after using
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
Log.e("TAG", data);
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
Posts.PostsDetails postsHelper = new Posts().new PostsDetails();
// For posts
try {
if (postsHelper.getIsPDCalled()){
JSONObject pJObj = new JSONObject(result);
JSONArray pJObjArray = pJObj.getJSONArray("posts");
for (int i = 0; i < pJObjArray.length(); i++) {
JSONObject pJObj_data = pJObjArray.getJSONObject(i);
postsHelper.setPost(pJObj_data.getInt("id"), "post_title", "post_content");
}
}
} catch (JSONException e) {
//Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
}
}
}
Login.java
public class Login extends AppCompatActivity {
Button LoginButton;
EditText uUserName, uPassWord;
WSAdapter.SendAPIRequests AuthHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//SetupHomeBtn = (ImageButton) findViewById(R.id.SetupHomeBtn);
LoginButton = (Button) findViewById(R.id.LoginButton);
uUserName = (EditText) findViewById(R.id.LoginUserBox);
uPassWord = (EditText) findViewById(R.id.LoginPassBox);
//AuthHelper = new WSAdapter().new SendDeviceDetails();
// Moves user to the main page after validation
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// gets the username and password from the EditText
String strUserName = uUserName.getText().toString();
String strPassWord = uPassWord.getText().toString();
// API url duh
String APIUrl = "http://192.168.0.18:8000/token-auth/";
// If the user is authenticated, then transfer to the MainActivity page
if (APIAuthentication(strUserName, strPassWord, APIUrl)){
startActivity(new Intent(Login.this, Posts.class));
}
}
});
}
private boolean APIAuthentication(String un, String pw, String url){
// when it wasn't static -> AuthHelper = new WSAdapter().new SendAPIRequests();
AuthHelper = new WSAdapter.SendAPIRequests();
JSONObject postData = new JSONObject();
try {
// Attempt to input info to the Django API
postData.put("username", un);
postData.put("password", pw);
// Putting the data to be posted in the Django API
AuthHelper.execute(url, postData.toString());
return true;
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
}
I was expecting my onPostExecute to be called and store data for my posts arrays.
Okay this is a nice example of async tasks. The problem here is when you call an async task then the code below will continue to execute even when the async task hasn't finished. So what happens in your case:
You fetch the posts and then ask to display them on the exact moment that the async function is still getting the posts. So of course the List is empty.
You can fix this by using the await keyword. This keyword stops the rest of your code from executing until that line has been executed. So change:
postDetailsHelper.callPostDetails("192.168.0.18:8000/api");
to:
await postDetailsHelper.callPostDetails("192.168.0.18:8000/api");
Now the reason that the login does work is because you call that function within the if statement. If you would store the return value of that function in a boolean first then it wouldn't work either.
Im new to android development have very basic knowledge of this whatever i have achieved till now is achieved using this website or youtube videos i'm stuck in AsyncTask (Earlier i was using .get() on Create View and it was working fine but UI Was blocked until task is finished. To Avoid UI Blocking i was advice to remove .get() function from OnCreateView() function now after removing this im not being able to get any data from AsyncTask). I did that but now i'm not being able to create view i did lots of research but unable to get this strength
Here is my Codes Please Help how to create view from this
OnCreateView() :-
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View GView = inflater.inflate(R.layout.fragment_dashboard, container, false);
progressBarHolder = (FrameLayout) GView.findViewById(R.id.progressBarHolder);
GridView gridView = (GridView) GView.findViewById(R.id.gridView);
//Toast.makeText(getActivity(),Json_String,Toast.LENGTH_LONG).show();
String finalResult = null;
try{
finalResult = String.valueOf(new JSONTask().execute("https://www.example.in/android_api/dashboard_data",JsonData()));
Toast.makeText(getActivity(),Json_String,Toast.LENGTH_LONG).show();
JSONObject parentObject = null;
parentObject = new JSONObject(finalResult);
if(((String) parentObject.names().get(0)).matches("error")){
JSONObject jObj = parentObject.getJSONObject("error");
errorThrow(jObj.getString("Description"));
} else if(((String) parentObject.names().get(0)).matches("success")){
JSONObject jObj = parentObject.getJSONObject("success");
JSONArray arrajson = jObj.getJSONArray("data");
String arrayCount = Integer.toString(arrajson.length());
String[] type = new String[arrajson.length()];
Integer[] count = new Integer[arrajson.length()];
for (int i=0; i<arrajson.length();i++){
JSONObject jsonObject = arrajson.getJSONObject(i);
type[i] = jsonObject.getString("type");
count[i] = jsonObject.getInt("count");
}
CustomAdpter customAdpter = new CustomAdpter(DashboardFragment.this,type,count);
gridView.setAdapter(customAdpter);
return GView;
}
} catch (JSONException e) {
e.printStackTrace();
}
return GView;
}
Base Adapter Code :-
class CustomAdpter extends BaseAdapter {
String[] type;
Integer[] count;
public CustomAdpter(DashboardFragment dashboardFragment, String[] type, Integer[] count){
this.count = count;
this.type = type;
}
#Override
public int getCount() {
return type.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = getLayoutInflater().inflate(R.layout.grid_single_itme,null);
TextView textView = (TextView) view.findViewById(R.id.TextView1);
TextView textView1 = (TextView) view.findViewById(R.id.textView2);
textView.setText(String.valueOf(count[i]));
textView1.setText(type[i]);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(),"Booking Item Clicked",Toast.LENGTH_LONG).show();
}
});
return view;
}
}
AsyncTask Code :-
public class JSONTask extends AsyncTask<String,String,String> {
private ProgressDialog mProgressDialog;
int progress;
public JSONTask(){
mProgressDialog = new ProgressDialog(getContext());
mProgressDialog.setMax(100);
mProgressDialog.setProgress(0);
}
#Override
protected void onPreExecute(){
mProgressDialog = ProgressDialog.show(getContext(),"Loading","Loading Data...",true,false);
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
final String finalJson = params[1];
String json = finalJson;
try{
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("A-APK-API", "******");
connection.setRequestProperty("Authorization", "Basic **:**");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.connect();
OutputStream stream = connection.getOutputStream();
OutputStreamWriter streams = new OutputStreamWriter(stream, "UTF-8");
stream.write(json.getBytes("UTF-8"));
stream.close();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
StringBuffer buffer = new StringBuffer();
String line = "";
while((line = reader.readLine()) != null){
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(connection != null){
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String result){
super.onPostExecute(result);
Json_String = result;
Toast.makeText(getContext(),result,Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}
}
Please help me here
You cannot get a result from asynctask when you dont use .get().
So change that statement. Start only the asynctask.
Then put all the code after that line in onPostExecute() of the AsyncTask.
Thats all.
you should change way you are creating the Adapter and attaching
you should do this
1.At first get the data in List,ArrayList etc. via AsyncTask, doInBackGround method
then on the onPostExecute method retrieve the data and create Adapter and attach it to your View
While you are getting data you can show some ProgressDialog.
If your AsyncTask is in other separate class then use interface to get the data from your AsyncTask class
look at this https://stackoverflow.com/a/47373959/8197737
I'm using android studio to get information from user and insert it into external DB, and i saw a lot of videos in youtube but still there is a problem when run it says: "registration success" but doesn't insert into DB
This is my code in android studio
public class signup extends AppCompatActivity {
EditText email,password,name;
Switch visually_impaired;
String Email,Password,Name,Visually_impaired,Beacon_alert,Buildings_alert;;
Context ctx = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
name = (EditText) findViewById(R.id.name_editText);
password = (EditText) findViewById(R.id.password_editText);
email = (EditText) findViewById(R.id.email_editText);
visually_impaired = (Switch) findViewById(R.id.blindOpt);
}
public void register(View v){
Email = email.getText().toString();
Name = name.getText().toString();
Password = password.getText().toString();
Visually_impaired = visually_impaired.getText().toString();
BackGround b = new BackGround(this);
b.execute(Email,Password,Name,Visually_impaired);
}
class BackGround extends AsyncTask<String,String,String> {
Context ctx;
public BackGround(Context ctx){
this.ctx = ctx;
}
#Override
protected String doInBackground(String... strings) {
String email = strings[0];
String password = strings[1];
String name = strings[2];
String visually_impaired = strings[3];
try {
URL url = new URL("http://ksuexpress.com/register.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
BufferedWriter bufferWriter = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
String data = URLEncoder.encode("email","UTF-8")+ " = "+URLEncoder.encode(email,"UTF-8") +"&"+
URLEncoder.encode("password","UTF-8")+ " = "+URLEncoder.encode(password,"UTF-8") +"&"+
URLEncoder.encode("name","UTF-8")+ " = "+URLEncoder.encode(name,"UTF-8") +"&"+
URLEncoder.encode("visually_impaired","UTF-8")+ " = "+URLEncoder.encode(visually_impaired,"UTF-8");
bufferWriter.write(data);
bufferWriter.flush();
bufferWriter.close();
os.close();
InputStream is = httpURLConnection.getInputStream();
is.close();
return "Registration success....";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result){
Toast.makeText(ctx,result,Toast.LENGTH_LONG).show();
}
}
}
and also i have a php code in server that uses POST and insert it to the DB
can anyone help me please ...
Some possible fixes:
change " = " to "=" without spaces
add some logs in doInBackground and make sure you're getting the correct parameters into email,password,etc.
change InputStream is = httpURLConnection.getInputStream(); is.close(); to httpURLConnection.connect();
I'm trying to send and receive data, but I have this error:
FATAL EXCEPTION: main
Process: smaa.smaa, PID: 4051
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
at android.support.v7.app.AlertDialog.resolveDialogTheme(AlertDialog.java:113)
at android.support.v7.app.AlertDialog$Builder.<init>(AlertDialog.java:291)
at smaa.smaa.BackgroundT.onPreExecute(BackgroundT.java:46)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:613)
at android.os.AsyncTask.execute(AsyncTask.java:560)
at smaa.smaa.FirstFragment.onClick(FirstFragment.java:44)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22260)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
This is my fragment:
public class FirstFragment extends Fragment implements View.OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_first, container, false);
Button btn1 = (Button)v.findViewById(R.id.btn1);
btn1.setOnClickListener(this);
return v;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn1:
String method = "see";
BackgroundT backgroundT = new BackgroundT(this);
backgroundT.execute(method);
break;
}
}
}
And my BackgroundTask:
public class BackgroundT extends AsyncTask<String,Void,String> {
AlertDialog alertDialog;
Context ctx;
String response = "";
private Context applicationContext;
private Context activity;
public BackgroundT(Context ctx) {
this.ctx = ctx;
}
public BackgroundT(FirstFragment firstFragment) {
this.ctx = ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
alertDialog = new AlertDialog.Builder(ctx).create();
alertDialog.setTitle("Ver Tickets");
}
#Override
protected String doInBackground(String... params) {
String see_url = "https://smaa.000webhostapp.com/androidver.php";
String method = params[0];
if (method.equals("see")) {
String login_name = params[1];
String login_pass = params[2];
String test = "test";
try {
URL url = new URL(see_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode("test", "UTF-8") + "=" + URLEncoder.encode(test, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
response += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx, response, Toast.LENGTH_LONG).show();
}
}
I know the problem is in the Context or ctx, but I don't know where, I've used something like this and it worked before so I don't know what is the problem now, here is a working version:
BackgroundTask: http://pastebin.com/UnxaSV2X
MainActivity: http://pastebin.com/rk5jufBc
--- EDIT ---
Thanks to #rafsanahmad007, here's what I fixed:
Fragment code:
String method = "see";
BackgroundT backgroundT = new BackgroundT(getActivity());
backgroundT.execute(method);
break;
BackgroundTask code:
public BackgroundT(FragmentActivity activity) {
this.ctx = activity;
}
There was also another error which I fixed later here:
String login_name = params[1];
String login_pass = params[2];
This was giving me an error because I wasn't using it, thanks everyone.
You need the Activity context to show a AlertDialog in Fragment
instead of;
BackgroundT backgroundT = new BackgroundT(this);
backgroundT.execute(method);
try this:
BackgroundT backgroundT = new BackgroundT(getActivity());
backgroundT.execute(method);
EDIT
Also Edit the constructor:
public BackgroundT(FragmentActivity activity) {
this.ctx = activity;
}
public BackgroundT(FirstFragment firstFragment) {
this.ctx = ctx;
}
pay attention ctx=ctx, so it is null and it fails when you construct the alert
I have a little issue about a little thing I don't understand.
It's just a simple request: how do I display an xml I just got in a thread?
There is my method postData to get the xml, I make it display in a log.v as you can see below in the code, but I can't display it to a TextView out of the thread.
public class RecupXml_Activity extends Activity {
TextView campagne;
String user = "toto";
String password = "tata";
String theCampagneXml;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
campagne = (TextView) findViewById(R.id.campagneTest);
postData(user, password);
}
public void postData(final String login, final String password) {
Thread background = new Thread(new Runnable() {
URL url;
String buffer;
String theCampagneXml = null;
#Override
public void run() {
try {
URLConnection urlConnection;
String body = "login=" + URLEncoder.encode(login, "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8");
url = new URL("http://3pi.tf/apps/sms/");
urlConnection = url.openConnection();
((HttpURLConnection) urlConnection).setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Content-Length", "" + body.length());
OutputStreamWriter writer = null;
BufferedReader reader = null;
writer = new OutputStreamWriter(urlConnection.getOutputStream());
writer.write(body);
writer.flush();
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while ((buffer = reader.readLine()) != null) {
theCampagneXml = buffer;
}
Log.v("test", "xml = " + theCampagneXml);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
campagne.post(new Runnable() {
#Override
public void run() {
campagne.setText("salut voici ta campagne : " + theCampagneXml);
}
});
}
});
background.start();
}
}
It appears in my Log but not in the TextView:/ I have a white empty Activity.
The problem is that you call postData() on UI-tread, meaning that the method also returns theCampagneXml on UI-thread, while your network operation goes on a worker thread. The following code with some changes and additions fixes the problem:
public class MainActivity extends Activity {
TextView campagne;
String user = "toto";
String password = "tata";
String theCampagneXml; // new
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
campagne = (TextView) findViewById(R.id.text);
postData(user, password); // new
}
public void postData(final String login, final String password) { // note: the return type has been changed
Thread background = new Thread(new Runnable() {
URL url;
String buffer;
String theCampagneXml = null; // new
#Override
public void run() {
try {
// no changes here but declaring `theCampagneXml` as class member
}
campagne.post(new Runnable() {
#Override
public void run() {
campagne.setText("hello, here is your XML : "+ theCampagneXml);
}
});
}
});
background.start();
}
}
Once the network operation is done and theCampagneXml is initialized, use post() for the TextView campagne that runs on UI-thread.
Additional info can be found in Processes and Threads.