What I want to achieve is the following:
In my view, I have 4 TextViews that should show the amount of items in the connected databases. This is done using a simple php script.
The problem I have is that I get all the correct values from the database, but when I try to set those values to my TextViews, the app crashes.
I have tried to look if using to many Asynctasks could be a problem, but when I decide to comment out the only line inside the SetTextForTextView() function, it all works like a charm and all the expected values are printed to my log. So with that being said, I dont think using multiple Asynctasks at the same time is the problem here, but I have really no idea what is.
Something that might be worth mentioning is when I comment out the following bit like this, the app doesn't crash...
shoesAmount = (TextView) findViewById(R.id.menuTvShoesAmount);
DatabaseTask taskA = new DatabaseTask(shoesAmount);
taskA.execute("getAmount", "shoes");
// tshirtsAmounts = (TextView) findViewById(R.id.menuTvTshirtsAmount);
// DatabaseTask taskB = new DatabaseTask(tshirtsAmounts);
// taskB.execute("getAmount", "tshirts");
//
// jeansAmount = (TextView) findViewById(R.id.menuTvJeansAmount);
// DatabaseTask taskC = new DatabaseTask(jeansAmount);
// taskC.execute("getAmount", "jeans");
//
// blousesAmount = (TextView) findViewById(R.id.menuTvBlousesAmount);
// DatabaseTask taskD = new DatabaseTask(blousesAmount);
// taskD.execute("getAmount", "blouses");
But then again with any other combination for example like this one, and the app crashes again...
// shoesAmount = (TextView) findViewById(R.id.menuTvShoesAmount);
// DatabaseTask taskA = new DatabaseTask(shoesAmount);
// taskA.execute("getAmount", "shoes");
//
tshirtsAmounts = (TextView) findViewById(R.id.menuTvTshirtsAmount);
DatabaseTask taskB = new DatabaseTask(tshirtsAmounts);
taskB.execute("getAmount", "tshirts");
//
// jeansAmount = (TextView) findViewById(R.id.menuTvJeansAmount);
// DatabaseTask taskC = new DatabaseTask(jeansAmount);
// taskC.execute("getAmount", "jeans");
//
// blousesAmount = (TextView) findViewById(R.id.menuTvBlousesAmount);
// DatabaseTask taskD = new DatabaseTask(blousesAmount);
// taskD.execute("getAmount", "blouses");
Does anyone can point me out into the direction where I might be going wrong?
Thanks!
(here is the full code)
package ishopper.theindiestudio.com.appname;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
public class Menu extends AppCompatActivity {
private ImageButton btnHelp, btnAccount, newest1, newest2, newest3;
private TextView shoesAmount, tshirtsAmounts, jeansAmount, blousesAmount;
private Button browseShoes, browseTshirts, browseJeans, browseBlouses;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
context = this;
btnHelp = (ImageButton) findViewById(R.id.menuBtnHelp);
btnAccount = (ImageButton) findViewById(R.id.menuBtnAccount);
btnAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onAccountOptions();
}
});
btnHelp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onHelp();
}
});
newest1 = (ImageButton) findViewById(R.id.menuIbNewest1);
newest2 = (ImageButton) findViewById(R.id.menuIbNewest2);
newest3 = (ImageButton) findViewById(R.id.menuIbNewest3);
//set newest items
shoesAmount = (TextView) findViewById(R.id.menuTvShoesAmount);
DatabaseTask taskA = new DatabaseTask(shoesAmount);
taskA.execute("getAmount", "shoes");
tshirtsAmounts = (TextView) findViewById(R.id.menuTvTshirtsAmount);
DatabaseTask taskB = new DatabaseTask(tshirtsAmounts);
taskB.execute("getAmount", "tshirts");
jeansAmount = (TextView) findViewById(R.id.menuTvJeansAmount);
DatabaseTask taskC = new DatabaseTask(jeansAmount);
taskC.execute("getAmount", "jeans");
blousesAmount = (TextView) findViewById(R.id.menuTvBlousesAmount);
DatabaseTask taskD = new DatabaseTask(blousesAmount);
taskD.execute("getAmount", "blouses");
}
public void SetTextForTextView(TextView textview, String result){
textview.setText(result);
}
public void onAccountOptions () {
Intent i = new Intent(this, AccountDetailsActivity.class);
startActivity(i);
}
public void onHelp () {
}
public void onBackPressed() {
//disabled back button
}
private class DatabaseTask extends AsyncTask<String, Void, String> {
private String taskType;
private String productType;
private TextView textView;
private ImageButton imageButton;
DatabaseTask (TextView mTextView){textView = mTextView;}
#Override
protected String doInBackground(String... params) {
String task = params[0];
if (task.equals("getAmount")) {
Log.e("doInBg", "getAmount");
String login_url = "http://url.eu/directory/script.php";
String tProductType = params[1];
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String postData = URLEncoder.encode("producttable", "UTF-8") + "=" + URLEncoder.encode(tProductType, "UTF-8");
bufferedWriter.write(postData);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
Log.e("doInBgResult", result.toString());
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
Menu activity = (Menu) context;
activity.SetTextForTextView(textView, result.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
}
The AsyncTask's doInBackground() runs in another thread and you can't change the UI from another thread, Only the main one. I suggest you do the same job in onPostExecute() after you finish your long job. Return the String result you want to use to the main thread
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
// no need for that
//Menu activity = (Menu) context;
//activity.SetTextForTextView(textView, result.toString());
reutrn result;
then update the text
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result != null){
SetTextForTextView(textView, result);
}
}
I suggest reading more about it from here and here
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
my app was working properly in this code all the city weather data show correctly. i want to add a toast for if someone enter a wrong city name
i can understand what is the error android studio dont give any error . if enter a city name works fine but if i enter a wrong city name or any other word it crashing
working code :::
package com.study.whatstheweather;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.inputmethod.InputMethod;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
EditText editText;
TextView textView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
textView2 = findViewById(R.id.textView2);
}
public void getweather (View view){
Downlordtask task = new Downlordtask();
task.execute("https://openweathermap.org/data/2.5/weather?q="+ editText.getText().toString()+ "&appid=439d4b804bc8187953eb36d2a8c26a02");
InputMethodManager methodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
methodManager.hideSoftInputFromWindow(editText.getWindowToken(),0);
}
public class Downlordtask extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try{
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while (data !=-1){ char curretnt = (char) data; result += curretnt; data = inputStreamReader.read(); } return result;}
catch (Exception e){e.printStackTrace();
return null; }
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
String wetherinfo = jsonObject.getString("weather");
Log.i("weather",wetherinfo);
JSONArray array = new JSONArray(wetherinfo);
String message="";
for (int i=0; i <array.length();i++){
JSONObject jsonPart = array.getJSONObject(i);
String main = jsonPart.getString("main");
String discrip = jsonPart.getString("description");
if (!main.equals("") && !discrip.equals("")){message += main + ":" + discrip + "\r\n";
}
}
if(!message.equals("")) { textView2.setText(message); }
} catch (Exception e){e.printStackTrace();}
}
}
}
then i enter the Toast in to this filed now app was crashing
crashing code ....
public class MainActivity extends AppCompatActivity {
EditText editText;
TextView textView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
textView2 = findViewById(R.id.textView2);
}
public void getweather (View view){
Downlordtask task = new Downlordtask();
task.execute("https://openweathermap.org/data/2.5/weather?q="+ editText.getText().toString()+ "&appid=439d4b804bc8187953eb36d2a8c26a02");
InputMethodManager methodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
methodManager.hideSoftInputFromWindow(editText.getWindowToken(),0);
}
public class Downlordtask extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try{
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while (data !=-1){ char curretnt = (char) data; result += curretnt; data = inputStreamReader.read(); } return result;}
catch (Exception e){e.printStackTrace();
Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_LONG).show();
return null; }
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
String wetherinfo = jsonObject.getString("weather");
Log.i("weather",wetherinfo);
JSONArray array = new JSONArray(wetherinfo);
String message="";
for (int i=0; i <array.length();i++){
JSONObject jsonPart = array.getJSONObject(i);
String main = jsonPart.getString("main");
String discrip = jsonPart.getString("description");
if (!main.equals("") && !discrip.equals("")){message += main + ":" + discrip + "\r\n";
}
}
if(!message.equals("")) { textView2.setText(message); }
} catch (Exception e){e.printStackTrace();}
}
}
} ```
You cannot make ui calls from a backgroud thread.Use android OS handler
So replace
Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_LONG).show();
with
new Handler().post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_LONG).show();
}
});
I'm trying to pass the matchday to the URL for the Http connection. I know I can't get a value from the EditText in the doInBackground method so I thought to get the value in the onPreExecute method. Of I then add the variable to the URL, the program doesn't recognise the String. I saw on StackOverflow you need to add the parameters in the execute method but I don't really have got that part of the explanation.
Does anyone have an idea how to add the matchday to the URL, entered in the EditText matchdayText?
Thanks in advance!
Rob Nickmans
CODE:
package ga.rndevelopment.footballpronostics;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
EditText matchdayText;
TextView responseView;
ProgressBar progressBar;
static final String API_KEY = "HIDDEN";
static final String API_URL = "http://api.football-data.org/v2/competitions/PL/matches/?matchday=";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
responseView = findViewById(R.id.responseView);
matchdayText = findViewById(R.id.matchdayText);
progressBar = findViewById(R.id.progressBar);
Button queryButton = findViewById(R.id.queryButton);
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new FetchData().execute();
}
});
}
class FetchData extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
String matchDay = matchdayText.getText().toString();
String apiUrl = API_URL + matchDay;
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(apiUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.addRequestProperty("X-Auth-Token", API_KEY);
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
} finally {
urlConnection.disconnect();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
#Override
protected void onPostExecute(String response) {
if (response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
}
}
}
First Create the connection using URL Connection.There by create
buffer writer and pass the all requested data in one single String
buffer variable there by it will take to concern URL and along with
Requested parameter and its values. Please go Through this Below
sample Example
URL url = new URL("give your URL ");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
final StringBuilder reqstData = new StringBuilder(100);
reqstData.append("&userId=").append(userId);
reqstData.append("&roleId=").append(roleId);
reqstData.append("&userName=").append(userName);
out.write(reqstData);
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
The problem is when i call Initialize()
public void Initialize(){
question.setText(test.get("question").get(index));
answer_1.setText(test.get("answer_1").get(index));
answer_2.setText(test.get("answer_2").get(index));
answer_3.setText(test.get("answer_3").get(index));
answer_4.setText(test.get("answer_4").get(index));
answer_5.setText(test.get("answer_5").get(index));
correct = test.get("answer_5").get(index);
index++;
}
at Sql_bridge asyncTask
#Override
protected void onPostExecute(HashMap<String,List<String>> stringList) {
if(!stringList.isEmpty()) {
test test = new test();
test.setTest(stringList);
test.Initialize();
}
else
Log.i("test","empty");
}
The thing is that test.setTest(stringList) works fine
Here is the full code
test.java
package com.example.littledev.gson;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.HashMap;
import java.util.List;
public class test extends AppCompatActivity {
private HashMap<String, List<String>> test;
TextView question;
Button answer_1, answer_2, answer_3, answer_4, answer_5;
String correct;
int index;
int score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
index = 0;
score = 0;
correct ="";
question = (TextView) findViewById(R.id.question);
answer_1 = (Button) findViewById(R.id.answer_1);
answer_2 = (Button) findViewById(R.id.answer_2);
answer_3 = (Button) findViewById(R.id.answer_3);
answer_4 = (Button) findViewById(R.id.answer_4);
answer_5 = (Button) findViewById(R.id.answer_5);
Sql_bridge bridge = new Sql_bridge();
bridge.execute("english");
}
public void onAnswer(View view){
if (index == test.get("question").size()) {
if (view.getTag().equals(correct))
score++;
Initialize();
}
else {
//startActivity(new Intent(test.this, Result.class));
Result result = new Result();
result.setScore(100*score/5);
}
}
public void Initialize(){
question.setText(test.get("question").get(index));
answer_1.setText(test.get("answer_1").get(index));
answer_2.setText(test.get("answer_2").get(index));
answer_3.setText(test.get("answer_3").get(index));
answer_4.setText(test.get("answer_4").get(index));
answer_5.setText(test.get("answer_5").get(index));
correct = test.get("answer_5").get(index);
index++;
}
public void setTest(HashMap<String, List<String>> map){
test = map;
}
}
Sql_bridge.java
package com.example.littledev.gson;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
class Sql_bridge extends AsyncTask<String, Void, HashMap<String,List<String>>> {
#Override
protected HashMap<String,List<String>> doInBackground(String... params) {
String reg_url = "http://e-shops.hol.es/app_test";
String response = "";
List<String> questions = new ArrayList<>();
List<String> answer_1 = new ArrayList<>();
List<String> answer_2 = new ArrayList<>();
List<String> answer_3 = new ArrayList<>();
List<String> answer_4 = new ArrayList<>();
List<String> answer_5 = new ArrayList<>();
List<String> correct = new ArrayList<>();
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
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(params[0], "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();
} catch (IOException e) {
e.printStackTrace();
}
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(response);
JSONArray jsonMainNode = jsonResponse.optJSONArray("result");
int lengthJsonArr = jsonMainNode.length();
Log.i("test",lengthJsonArr + " length");
for(int i=0; i < lengthJsonArr; i++)
{
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
questions.add(jsonChildNode.optString("question"));
answer_1.add(jsonChildNode.optString("answer_1"));
answer_2.add(jsonChildNode.optString("answer_2"));
answer_3.add(jsonChildNode.optString("answer_3"));
answer_4.add(jsonChildNode.optString("answer_4"));
answer_5.add(jsonChildNode.optString("answer_5"));
correct.add(jsonChildNode.optString("correct"));
}
} catch (JSONException e) {
e.printStackTrace();
}
HashMap<String, List<String>> test = new HashMap<>();
test.put("question",questions);
test.put("answer_1",answer_1);
test.put("answer_2",answer_2);
test.put("answer_3",answer_3);
test.put("answer_4",answer_4);
test.put("answer_5",answer_5);
test.put("correct",correct);
return test;
}
#Override
protected void onPostExecute(HashMap<String,List<String>> stringList) {
if(!stringList.isEmpty()) {
test test = new test();
test.setTest(stringList);
test.Initialize();
}
else
Log.i("test","empty");
}
}
logcat
04-09 20:15:38.832 10470-10470/com.example.littledev.gson E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.littledev.gson, PID: 10470
java.lang.NullPointerException
at com.example.littledev.gson.test.Initialize(test.java:57)
at com.example.littledev.gson.Sql_bridge.onPostExecute(Sql_bridge.java:104)
at com.example.littledev.gson.Sql_bridge.onPostExecute(Sql_bridge.java:25)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5433)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
You're trying to create an Activity using a constructor, which is not allowed. You'll always get a NullPointerException if you keep doing that, because you're Activity won't get created so the reference to the view inside the Initialize method is null. Please, take a look at how to start an Activity
What you should be doing is creating an Intent, putting the string you need in that Activity inside the Intent, then launch the Activity using context.startActivity(intent)
Another possibility is to provide your AsyncTask with a callback to your activity.
public class Sql_bridge extends AsyncTask<String, Void, HashMap<String,List<String>>>
{
public interface SqlBridgeListener
{
/**
* Called when your query is completed.
* #param stringList Result list.
*/
void onQueryCompleted(HashMap<String,List<String>> stringList);
}
/**
* Store listener as a weak reference to not leak the resource.
*/
private WeakReference<SqlBridgeListener> mListener;
public SqlBridge(SqlBridgeListener listener)
{
mListener = new WeakReference<SqlBridgeListener>(listener);
}
#Override
protected HashMap<String, List<String>> doInBackground(String... strings)
{
// Same code as your post, not shown for brevity.
}
#Override
protected void onPostExecute(HashMap<String,List<String>> stringList) {
if(!stringList.isEmpty())
{
SqlBridgeListener listener = mListener.get();
if(listener != null)
{
// Notify listener with results.
listener.onQueryCompleted(stringList);
}
}
}
}
Then on your activity:
public class test extends AppCompatActivity implements Sql_bridge.SqlBridgeListener {
private HashMap<String, List<String>> test;
TextView question;
Button answer_1, answer_2, answer_3, answer_4, answer_5;
String correct;
int index;
int score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
index = 0;
score = 0;
correct ="";
question = (TextView) findViewById(R.id.question);
answer_1 = (Button) findViewById(R.id.answer_1);
answer_2 = (Button) findViewById(R.id.answer_2);
answer_3 = (Button) findViewById(R.id.answer_3);
answer_4 = (Button) findViewById(R.id.answer_4);
answer_5 = (Button) findViewById(R.id.answer_5);
// Provide activity as a listener.
Sql_bridge bridge = new Sql_bridge(this);
bridge.execute("english");
}
#Override
public void onQueryCompleted(HashMap<String,List<String>> stringList)
{
// Update your views with the result.
}
// Rest of the activity not shown for brevity.
Thanks to #quiro i did it. I passed the context as a parameter
private Context ctx;
Sql_bridge(Context ctx) {
this.ctx = ctx;
}
and then used
if(ctx instanceof Test){
((Test) ctx).Initialize();
}
Thank you for the help.
I am having a problem.
I can't figure out why the following code won't work.
It's a simple app that sends a GET request to some php fragment that supposed to insert a row in a table.
I can't understand why it doesn't work.
Please help.
java:
package com.example.michael.biyum;
import android.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
final AlertDialog alertDialog = alertDialogBuilder.create();
Button startBtn = (Button) findViewById(R.id.btn);
final TextView t = (TextView) findViewById(R.id.hello);
startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://www.chatty.co.il/biyum.php?q=mkyong");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
Toast.makeText(getApplicationContext(),"GET:"+current,Toast.LENGTH_LONG).show();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
});
}
}
php:
<?php
require('connect.inc.php');
$update_offline="INSERT INTO offline_waiters (user_partner,mail,chat_room) VALUES(0,'gavno','gavno')";
$query_run= mysqli_query($conn,$update_offline);
echo "new";
?>
It's a simple test that should enter a new row in my table.
When I make the request manualy via a browser it works fine.
Once again please help me understand where is the problem.
You need to get the network operation off of the main thread.
I just got this working and tested using an AsyncTask:
class MyAsyncTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
StringBuilder result = new StringBuilder();
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://www.chatty.co.il/biyum.php?q=mkyong");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
result.append(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return result.toString();
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(),"GET:"+result,Toast.LENGTH_LONG).show();
}
}
Just execute the AsyncTask from your click listener:
startBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
new MyAsyncTask().execute();
});
Result in the Toast:
I'm getting a null pointer exception on the line marked with /Here/ in my code. I've spent about 2 hours looking up the AssetManager and how to use it, etc, but still can't figure out why it's null. I've called getAssets() by itself, from the context and from the resources but still I'm getting null. Can anyone help me out here?
Thanks.
package com.hamc17.CatFacts;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class FactsActivity extends Activity{
Context context;
Resources res;
#Override
public void onCreate(Bundle savedInstanceBundle){
super.onCreate(savedInstanceBundle);
context = getApplicationContext();
res = context.getResources();
Button getFactButton = (Button) findViewById(R.id.getFactButton);
getFactButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast toastMessageOnClick = new Toast(FactsActivity.this);
toastMessageOnClick.setText(getFact());
if((toastMessageOnClick.toString()).length()>50)
{
toastMessageOnClick.setDuration(10);
}
else
{
toastMessageOnClick.setDuration(Toast.LENGTH_LONG);
}
toastMessageOnClick.show();
}
});
}
String[] factArray = getFactsFromTextFile().split(";");
private String getFactsFromTextFile(){
/*Here*/ AssetManager assMan = context.getAssets();
try{
BufferedReader buff = new BufferedReader(new InputStreamReader(assMan.open("facts.txt")));
String line;
StringBuilder build = new StringBuilder();
while((line = buff.readLine()) != null)
{
build.append(line).append(System.getProperty("line.seperator"));
}
return build.toString();
}
catch (IOException e)
{
Toast toastMessage = new Toast(getApplicationContext());
toastMessage.setText(e.toString() + "\n Whoops, there was an error! ");
toastMessage.show();
return "";
}
finally
{
try{
assMan.close();
}
catch (Exception e)
{
//Whatever Trevor
}
}
}
private String getFact(){
String randomFactString = "";
int factCount = factArray.length;
Random rng = new Random();
int randomNum = rng.nextInt()*factCount;
randomFactString = factArray[randomNum];
return randomFactString;
}
}
You are missing setContentView(R.layout.mylayout);
#Override
public void onCreate(Bundle savedInstanceBundle){
super.onCreate(savedInstanceBundle);
setContentView(R.layout.mylayout);
Button getFactButton = (Button) findViewById(R.id.getFactButton);
findViewById looks for a resource with the id in the current inflated layout. So you should set the content of your layout to the activity before initializing views
Also you can use
res = getResources();
Instead of creating a local variable to get the Context of the Activity just use getBaseContext(); each time you want to get the reference to the Context.
So something like this instead:
AssetManager assMan = getBaseContext().getAssets();