Why do I get NullPointerException from AsyncTask? [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am trying to create an Android app for weather. After some failed results, I decided to try a code from the internet. It still doesn't work.
I found it here: https://androstock.com/tutorials/create-a-weather-app-on-android-android-studio.html
The error I'm getting is:
I have checked the url with my actual API key - in browser it works.
MainActivity:
public class MainActivity extends AppCompatActivity {
TextView selectCity, cityField, detailsField, currentTemperatureField, humidity_field, pressure_field, weatherIcon, updatedField;
ProgressBar loader;
Typeface weatherFont;
String city = "Rome, IT";
/* Please Put your API KEY here */
String OPEN_WEATHER_MAP_API = "f2b6e17d5a21b6580934286ac8fa696a";
/* Please Put your API KEY here */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loader = (ProgressBar) findViewById(R.id.loader);
selectCity = (TextView) findViewById(R.id.selectCity);
cityField = (TextView) findViewById(R.id.city_field);
updatedField = (TextView) findViewById(R.id.updated_field);
detailsField = (TextView) findViewById(R.id.details_field);
currentTemperatureField = (TextView) findViewById(R.id.current_temperature_field);
humidity_field = (TextView) findViewById(R.id.humidity_field);
pressure_field = (TextView) findViewById(R.id.pressure_field);
weatherIcon = (TextView) findViewById(R.id.weather_icon);
weatherFont = Typeface.createFromAsset(getAssets(), "fonts/weathericons-regular-webfont.ttf");
weatherIcon.setTypeface(weatherFont);
taskLoadUp(city);
selectCity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle("Change City");
final EditText input = new EditText(MainActivity.this);
input.setText(city);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
alertDialog.setView(input);
alertDialog.setPositiveButton("Change",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
city = input.getText().toString();
taskLoadUp(city);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
});
}
public void taskLoadUp(String query) {
if (Function.isNetworkAvailable(getApplicationContext())) {
Log.w("myApp", "network available in main 91");
DownloadWeather task = new DownloadWeather();
task.execute(query);
} else {
Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_LONG).show();
}
}
class DownloadWeather extends AsyncTask < String, Void, String > {
#Override
protected void onPreExecute() {
super.onPreExecute();
loader.setVisibility(View.VISIBLE);
}
protected String doInBackground(String...args) {
String xml = Function.excuteGet("http://api.openweathermap.org/data/2.5/weather?q=" + args[0] +
"&units=metric&appid=" + OPEN_WEATHER_MAP_API);
Log.w("myApp", "xml is " +xml);
return xml;
}
#Override
protected void onPostExecute(String xml) {
try {
JSONObject json = new JSONObject(xml);
if (json != null) {
JSONObject details = json.getJSONArray("weather").getJSONObject(0);
JSONObject main = json.getJSONObject("main");
DateFormat df = DateFormat.getDateTimeInstance();
cityField.setText(json.getString("name").toUpperCase(Locale.US) + ", " + json.getJSONObject("sys").getString("country"));
detailsField.setText(details.getString("description").toUpperCase(Locale.US));
currentTemperatureField.setText(String.format("%.2f", main.getDouble("temp")) + "°");
humidity_field.setText("Humidity: " + main.getString("humidity") + "%");
pressure_field.setText("Pressure: " + main.getString("pressure") + " hPa");
updatedField.setText(df.format(new Date(json.getLong("dt") * 1000)));
weatherIcon.setText(Html.fromHtml(Function.setWeatherIcon(details.getInt("id"),
json.getJSONObject("sys").getLong("sunrise") * 1000,
json.getJSONObject("sys").getLong("sunset") * 1000)));
loader.setVisibility(View.GONE);
}else{
Toast.makeText(getApplicationContext(), "Json variable is null", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error, Check City", Toast.LENGTH_SHORT).show();
}
}
}
}
Function:
public class Function {
// Project Created by Ferdousur Rahman Shajib
// www.androstock.com
public static boolean isNetworkAvailable(Context context)
{
return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
}
public static String excuteGet(String targetURL)
{
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("content-type", "application/json; charset=utf-8");
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(false);
InputStream is;
int status = connection.getResponseCode();
if (status != HttpURLConnection.HTTP_OK)
is = connection.getErrorStream();
else
is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
public static String setWeatherIcon(int actualId, long sunrise, long sunset){
int id = actualId / 100;
String icon = "";
if(actualId == 800){
long currentTime = new Date().getTime();
if(currentTime>=sunrise && currentTime<sunset) {
icon = "";
} else {
icon = "";
}
} else {
switch(id) {
case 2 : icon = "";
break;
case 3 : icon = "";
break;
case 7 : icon = "";
break;
case 8 : icon = "";
break;
case 6 : icon = "";
break;
case 5 : icon = "";
break;
}
}
return icon;
}
}
The output:
FATAL EXCEPTION: main
Process: com.example.weatherapp, PID: 30032
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:159)
at org.json.JSONObject.<init>(JSONObject.java:176)
at com.example.weatherapp.MainActivity$DownloadWeather.onPostExecute(MainActivity.java:117)
at com.example.weatherapp.MainActivity$DownloadWeather.onPostExecute(MainActivity.java:101)
at android.os.AsyncTask.finish(AsyncTask.java:695)
at android.os.AsyncTask.access$600(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2019-02-09 18:27:45.489 30032-30032/com.example.weatherapp I/Process: Sending signal. PID: 30032 SIG: 9
The app begins to start, but then closes immediately.
EDIT: The question should not be a duplicate, in my opinion, as the problem is not from wrong initialization of an object, but from not adding a specific line in the manifest file

The issue can be with the permission for internet and permission for cleartext HTTP traffic value in your manifest.
Please make sure to add
?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="true"
...>
...
</application>
</manifest>

Related

Fatal Error java.lang.IllegalStateException: Could not execute method for android:onClick [duplicate]

This question already has answers here:
android.content.ActivityNotFoundException:
(24 answers)
Closed 4 years ago.
The following error i faced
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.standardcoach.ticketing, PID: 12763
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.view.View$DeclaredOnClickListener.onClick(View.java:4505)
at android.view.View.performClick(View.java:5265)
at android.view.View$PerformClick.run(View.java:21534)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5765)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.view.View$DeclaredOnClickListener.onClick(View.java:4500)
at android.view.View.performClick(View.java:5265) 
at android.view.View$PerformClick.run(View.java:21534) 
at android.os.Handler.handleCallback(Handler.java:815) 
at android.os.Handler.dispatchMessage(Handler.java:104) 
at android.os.Looper.loop(Looper.java:207) 
at android.app.ActivityThread.main(ActivityThread.java:5765) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679) 
Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.standardcoach.ticketing/com.standardcoach.ticketing.ParcelActivity}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1805)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1523)
at android.app.Activity.startActivityForResult(Activity.java:3968)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
at android.app.Activity.startActivityForResult(Activity.java:3920)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
at android.app.Activity.startActivity(Activity.java:4259)
at android.app.Activity.startActivity(Activity.java:4227)
at com.standardcoach.ticketing.MainActivity.parcels(MainActivity.java:189)
at java.lang.reflect.Method.invoke(Native Method) 
at android.view.View$DeclaredOnClickListener.onClick(View.java:4500) 
at android.view.View.performClick(View.java:5265) 
at android.view.View$PerformClick.run(View.java:21534) 
at android.os.Handler.handleCallback(Handler.java:815) 
at android.os.Handler.dispatchMessage(Handler.java:104) 
at android.os.Looper.loop(Looper.java:207) 
at android.app.ActivityThread.main(ActivityThread.java:5765) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679) 
On executing my class through mainActivity i suffer from above error that says there is a problem on line number 189 which is
startActivity(new Intent(getApplicationContext(), ParcelActivity.class));
Below is my main activity for button to click that is main_activity.xml
<android.support.v7.widget.AppCompatButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:layout_marginBottom="24dp"
android:padding="12dp"
android:onClick="parcels"
android:background="#color/white"
android:textSize="24dip"
android:text="PARCELS(MIZIGO)"/>
My class on mainActivity class is
public void parcels(View view) {
if (LoginActivity.scanTicket.equalsIgnoreCase("Yes")) {
startActivity(new Intent(getApplicationContext(), ParcelActivity.class));
} else {
dialogMessage("parcel Activity Access Denied");
}}
The following is a class to be called by parcels class in mainActivity
parcelActivity.java is
public class ParcelActivity
extends AppCompatActivity
{
private static String POST_URL;
EditText parcelNameBox;
EditText senderNameBox;
EditText senderPhoneBox;
EditText receiverNameBox;
EditText receiverPhoneBox;
EditText parcelFromBox;
EditText parcelToBox;
EditText parcelAmountBox;
EditText shipDateBox;
EditText parcelBusNumberBox;
String parcelName;
String senderName;
String senderPhone;
String receiverName;
String receiverPhone;
String parcelFrom;
String parcelTo;
String parcelAmountPaid;
String shipDate;
String parcelBusNumber;
private ProgressDialog progress;
private String capitalize(String paramString)
{
StringBuffer localStringBuffer = new StringBuffer();
Matcher localMatcher = Pattern.compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(paramString);
while (localMatcher.find()) {
localMatcher.appendReplacement(localStringBuffer, localMatcher.group(1).toUpperCase() + localMatcher.group(2).toLowerCase());
}
return localMatcher.appendTail(localStringBuffer).toString();
}
void dialogMessage(String paramString)
{
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
localBuilder.setMessage(paramString);
localBuilder.setCancelable(false);
localBuilder.setNegativeButton("Okay", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
paramAnonymousDialogInterface.cancel();
}
});
localBuilder.create().show();
}
public void onBackPressed()
{
super.onBackPressed();
startActivity(new Intent(getApplicationContext(), ChooseSeatActivity.class));
}
protected void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("RECORD PARCEL");
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
setContentView(R.layout.activity_record_parcel);
POST_URL = LoginActivity.base_url + "Webservice/parcel";
this.parcelNameBox = ((EditText)findViewById(R.id.parcelNameBox));
this.senderNameBox = ((EditText)findViewById(R.id.senderNameBox));
this.senderPhoneBox = ((EditText)findViewById(R.id.senderPhoneBox));
this.receiverNameBox = ((EditText)findViewById(R.id.receiverNameBox));
this.receiverPhoneBox = ((EditText)findViewById(R.id.receiverPhoneBox));
this.parcelFromBox = ((EditText)findViewById(R.id.parcelFromBox));
this.parcelToBox = ((EditText)findViewById(R.id.parcelToBox));
this.parcelAmountBox = ((EditText)findViewById(R.id.parcelAmountBox));
this.shipDateBox = ((EditText)findViewById(R.id.shipDateBox));
this.parcelBusNumberBox = ((EditText)findViewById(R.id.parcelBusNumberBox));
}
public void registerParcel(View paramView)
{
this.parcelName = this.parcelNameBox.getText().toString();
this.parcelName = capitalize(this.parcelName);
this.senderName = this.senderNameBox.getText().toString();
this.senderName = capitalize(this.senderName);
this.senderPhone = this.senderPhoneBox.getText().toString();
this.receiverName = this.receiverNameBox.getText().toString();
this.receiverName = capitalize(this.receiverName);
this.receiverPhone = this.receiverPhoneBox.getText().toString();
this.parcelFrom = this.parcelFromBox.getText().toString();
this.parcelFrom = capitalize(this.parcelFrom);
this.parcelTo = this.parcelToBox.getText().toString();
this.parcelTo = capitalize(this.parcelTo);
this.parcelAmountPaid = this.parcelAmountBox.getText().toString();
this.shipDate = this.shipDateBox.getText().toString();
this.parcelBusNumber = this.parcelBusNumberBox.getText().toString();
Constants.parcelName = this.parcelName;
Constants.senderName = this.senderName;
Constants.senderPhone = this.senderPhone;
Constants.receiverName = this.receiverName;
Constants.receiverPhone = this.receiverPhone;
Constants.parcelFrom = this.parcelFrom;
Constants.parcelTo = this.parcelTo;
Constants.parcelAmountPaid = this.parcelAmountPaid;
Constants.shipDate = this.shipDate;
Constants.parcelBusNumber = this.parcelBusNumber;
if ((this.parcelName.length() > 0) && (this.senderName.length() > 0) && (this.senderPhone.length() > 0) && (this.receiverName.length() > 0) && (this.receiverPhone.length() > 0) && (this.parcelFrom.length() > 0) && (this.parcelTo.length() > 0) && (this.parcelAmountPaid.length() > 0)&& (this.shipDate.length() > 0) && (this.parcelBusNumber.length() > 0))
{
if (this.senderPhone.length() == 12 && this.receiverPhone.length() == 12)
{
new PostClass(this).execute(parcelName,senderName,senderPhone,receiverName,receiverPhone,parcelFrom,parcelTo,parcelAmountPaid,shipDate,parcelBusNumber);
return;
}
dialogMessage("Weka Namba ya Simu Sahihi");
return;
}
dialogMessage("Hakikisha Umejaza Taarifa Zote za Mzigo");
}
private class PostClass extends AsyncTask<String, Void, String> {
private final Context context;
String result = "";
public PostClass(Context c) {
this.context = c;
}
protected void onPreExecute() {
ParcelActivity.this.progress = new ProgressDialog(this.context);
ParcelActivity.this.progress.setCancelable(false);
ParcelActivity.this.progress.setMessage("Please Wait.....");
ParcelActivity.this.progress.show();
}
protected String doInBackground(String... params) {
try {
HttpURLConnection connection = (HttpURLConnection) new URL(ParcelActivity.POST_URL).openConnection();
String urlParameters = "parcelName=" + ParcelActivity.this.parcelName +
"&&senderName=" + ParcelActivity.this.senderName +
"&&senderPhone=" + ParcelActivity.this.senderPhone +
"&&receiverName=" + ParcelActivity.this.receiverName +
"&&receiverPhone=" + ParcelActivity.this.receiverPhone +
"&&parcelFrom=" + ParcelActivity.this.parcelFrom +
"&&parcelTo=" + ParcelActivity.this.parcelTo +
"&&parcelAmount=" + ParcelActivity.this.parcelAmountPaid +
"&&shipDate=" + ParcelActivity.this.shipDate +
"&&agentName=" + LoginActivity.agentName +
"&&agentPhone=" + LoginActivity.agentPhone +
"&&parcelBusNumber=" + ParcelActivity.this.parcelBusNumber;
connection.setRequestMethod("POST");
connection.setDoOutput(true);
DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
dStream.writeBytes(urlParameters);
dStream.flush();
dStream.close();
StringBuilder output = new StringBuilder("");
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder responseOutput = new StringBuilder();
while (true) {
line = br.readLine();
if (line == null) {
break;
}
responseOutput.append(line);
}
br.close();
output.append(responseOutput.toString());
this.result = responseOutput.toString();
} catch (MalformedURLException e) {
this.result = e.getMessage();
} catch (IOException e2) {
this.result = e2.getMessage();
}
return this.result;
}
protected void onPostExecute(String result) {
ParcelActivity.this.progress.dismiss();
System.out.println(result);
try {
JSONObject jsonObj = new JSONObject(result);
String parcelNumber = jsonObj.getString("parcelNumber");
Constants.parcelTicket = parcelNumber;
// Constants.agentCode = LoginActivity.agentCode;
if (LoginActivity.agentGroup.equalsIgnoreCase("Agent") || LoginActivity.agentGroup.equalsIgnoreCase("All")) {
ParcelActivity.this.startActivity(new Intent(ParcelActivity.this.getApplicationContext(), PrintParcelActivity.class));
} else {
ParcelActivity.this.dialogMessage("Try Again...");
}
} catch (JSONException e) {
ParcelActivity.this.dialogMessage("Jaribu Tena..Kuna Tatizo");
Log.d("ERROR: ", e.getLocalizedMessage());
}
}
}
As the error says
Caused by: android.content.ActivityNotFoundException: Unable to find
explicit activity class
{com.standardcoach.ticketing/com.standardcoach.ticketing.ParcelActivity};
have you declared this activity in your AndroidManifest.xml?
Add your Activity in your manifest.xml file.
<activity
android:name="com.standardcoach.ticketing.ParcelActivity"/>

Getting Error java.lang.IllegalArgumentException: unexpected url

Hi i am trying to send some data to server by using json parsing but activity is getting crashed and it leads to
java.lang.IllegalArgumentException: unexpected url
This is My Activity Code and i am commenting the lines where i am getting the Errors.
public class LoginActivity extends AppCompatActivity { **// Showing Error at this LIne**
public Location location;
private Button btnLogin;
private boolean doubleBackToExitPressedOnce = false;
private EditText phoneNo, password;
private CheckBox cbShow, cbRemember;
private NetworkUtil networkUtil;
private SharePrefUtil sharePref;
private LocationInfo locationInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
networkUtil = new NetworkUtil(getApplicationContext());
sharePref = new SharePrefUtil(getApplicationContext());
initScreen();
if (sharePref.getValueFromSharePref("remeberFlag").equalsIgnoreCase("true")) {
phoneNo.setText(sharePref.getValueFromSharePref("mobileno"));
password.setText(sharePref.getValueFromSharePref("password"));
cbRemember.setChecked(true);
}
}
private void initScreen() {
LocationLibrary.showDebugOutput(true);
try {
LocationLibrary.initialiseLibrary(LoginActivity.this, 60 * 1000, 60 * 1000 * 2, "com.aspeage.jagteraho");
} catch (UnsupportedOperationException e) {
Toast.makeText(this, "Device doesn't have any location providers", Toast.LENGTH_LONG).show();
}
phoneNo = (EditText) findViewById(R.id.ed_phoneno);
password = (EditText) findViewById(R.id.ed_password);
cbRemember = (CheckBox) findViewById(R.id.cbox_rememberme);
cbRemember.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) sharePref.setValueInSharePref("remeberFlag", "true");
else sharePref.setValueInSharePref("remeberFlag", "false");
}
});
cbShow = (CheckBox) findViewById(R.id.cbox_showpass);
cbShow.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
} else {
password.setInputType(129);
}
}
});
btnLogin = (Button) findViewById(R.id.btn_login);
btnLogin.setOnClickListener(new ButtonClick());
}
private class ButtonClick implements View.OnClickListener {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_login:
btnLoginClicked();
break;
default:
break;
}
}
}
private void btnLoginClicked() {
if(phoneNo.getText().toString().trim().equals("admin") && password.getText().toString().trim().equals("admin")) {
loginService();
}
if (validation()) {
if (cbRemember.isChecked())
rememberMe(password.getText().toString().trim());
if (networkUtil.isConnected()) {
loginService();
} else {
new SweetAlertDialog(LoginActivity.this, cn.pedant.SweetAlert.SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText("No Network Connection")
.show();
}
}
}
/**
* save username and password in SharedPreferences.
*
* #param //password is key value for storing in SharedPreferences.
*/
public void rememberMe(String password) {
SharePrefUtil sharePref = new SharePrefUtil(getApplicationContext());
sharePref.setValueInSharePref("password", password);
}
private boolean validation() {
int errorCount = 0;
if (phoneNo.getText().toString().trim().equals("")
|| phoneNo.getText().length() != 10) {
phoneNo.setError("Enter valid phone number");
errorCount = errorCount + 1;
if (errorCount == 1) {
phoneNo.requestFocus();
}
} else {
phoneNo.setError(null);
}
if (password.getText().toString().trim().equals("")
|| password.getText().length() != 12) {
password.setError("Enter valid password");
errorCount = errorCount + 1;
if (errorCount == 1) {
password.requestFocus();
}
} else {
password.setError(null);
}
if (errorCount == 0) {
return true;
} else {
return false;
}
}
private void batteryTimer(){
Timer timer = new Timer();
TimerTask hourlyTask = new TimerTask() {
#Override
public void run() {
if (networkUtil.isConnected()) {
batteryLevelCheckService(); // **Getting Error at this Line**
}
else {
offlineBatteryStatus();
}
}
};
timer.scheduleAtFixedRate(hourlyTask, 01, 60000);
}
private void batteryLevelCheckService() {
OkHttpClient client = new OkHttpClient();
String requestURL = String.format(getResources().getString(R.string.service_batteryLevelCheckService));
JSONArray jsonArrayRequest = new JSONArray();
JSONObject jsonRequest;
try {
List<BatteryStatusModel> batStatusOffline = new Select().from(BatteryStatusModel.class).execute();
if (batStatusOffline.size() > 0) {
for (BatteryStatusModel batStatusObject : batStatusOffline) {
jsonRequest = new JSONObject();
jsonRequest.accumulate("strTime", batStatusObject.batStatTime);
jsonRequest.accumulate("batteryStatusLat", "" + batStatusObject.battery_lat);
jsonRequest.accumulate("batteryStatusLog", "" + batStatusObject.battery_lon);
jsonRequest.accumulate("empAuthKey", sharePref.getValueFromSharePref("authKey"));
jsonRequest.accumulate("mobno", "" + sharePref.getValueFromSharePref("mobileno"));
jsonRequest.accumulate("strBatteryStatus", "" + batStatusObject.batteryStatus);
jsonArrayRequest.put(jsonRequest);
}
}
Intent intent = this.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
int percent = (level * 100) / scale;
Date today = Calendar.getInstance().getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
String time = simpleDateFormat.format(today);
jsonRequest = new JSONObject();
jsonRequest.accumulate("strTime", time);
jsonRequest.accumulate("batteryStatusLat", "" + locationInfo.lastLat);
jsonRequest.accumulate("batteryStatusLon", "" + locationInfo.lastLong);
jsonRequest.accumulate("empAuthKey", sharePref.getValueFromSharePref("authKey"));
jsonRequest.accumulate("mobNo", "" + sharePref.getValueFromSharePref("mobileno"));
jsonRequest.accumulate("strBatteryStatus", "" + percent);
jsonArrayRequest.put(jsonRequest);
} catch (Exception e) {
e.printStackTrace();
}
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonArrayRequest.toString());
Request request = new Request.Builder()
.url(requestURL) // Getting Error at this Line
.post(body).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String responseString = response.body().string();
try {
JSONObject jsonResponse = new JSONObject(responseString);
String status = jsonResponse.getString("status");
String message = jsonResponse.getString("message");
Log.d("jagteraho", "response :: status: " + status.toString() + " message: " + message);
if (status.equals("success")) {
new Delete().from(BatteryStatusModel.class).execute();
} else if (status.equals("failure")) {
} else if (status.equals("error")) {
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
This is my Logcat
java.lang.IllegalArgumentException: unexpected url: >http://192.168.2.20:8080/jagteraho/batteryStatus/save
at okhttp3.Request$Builder.url(Request.java:143)
at com.aspeage.jagteraho.LoginActivity.batteryLevelCheckService(LoginActivity.java:270)
at com.aspeage.jagteraho.LoginActivity.access$600(LoginActivity.java:59)
at com.aspeage.jagteraho.LoginActivity$4.run(LoginActivity.java:216)
at java.util.Timer$TimerImpl.run(Timer.java:284)
Please help me with the possible solutions i am quite new in Android Development
Your error is coming from OkHttp.
If you search for the error message, you can see where OkHttp is generating it:
https://github.com/square/okhttp/blob/master/okhttp/src/main/java/okhttp3/Request.java#L142
HttpUrl parsed = HttpUrl.parse(url);
if (parsed == null) throw new IllegalArgumentException("unexpected url: " + url);
return url(parsed);
It means that your URL is invalid. As the comment to your question points out: >http://192.168.2.20:8080/jagteraho/batteryStatus/save is not a valid URL.
You need to remove the >.

API Not Searching Food Database When Clicking The Search Button get error Permission denied

Hey Guys I'm working on a calorie app where the user clicks the search button and it supposed to retrieve information from the USDA Food Composition Databases API. For some reason it doesnt do anything and I noticed I get an error in the Logcat.
Im new to Android and to API. Thanks again in advance..
logcat :
Here is the logcat Error I'm Getting
AddEntry.java
public class AddEntry extends Fragment implements View.OnClickListener {
EditText FoodET,CalorieET;
ImageButton Savebtn, Cancelbtn;
Button searchbutton;
String foodET,calorieET;
//database
private DatabaseHandler dba;
public AddEntry() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_add_entry, container,
false);
Savebtn = (ImageButton) myView.findViewById(R.id.SaveBtn);
Savebtn.setBackgroundColor(Color.TRANSPARENT);
Savebtn.setOnClickListener(this);
searchbutton = (Button) myView.findViewById(R.id.SearchButton);
searchbutton.setOnClickListener(this);
Cancelbtn = (ImageButton) myView.findViewById(R.id.CancelBtn);
Cancelbtn.setBackgroundColor(Color.TRANSPARENT);
Cancelbtn.setOnClickListener(this);
return myView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
FoodET= (EditText)view.findViewById(R.id.foodEditText);
FoodET.setInputType(InputType.TYPE_CLASS_TEXT);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
CalorieET.setInputType(InputType.TYPE_CLASS_NUMBER);
foodET = ((EditText)
view.findViewById(R.id.foodEditText)).getText().toString();
calorieET = ((EditText)
view.findViewById(R.id.caloriesEditText)).getText().toString();
}
public void saveDataToDB (){
Food food = new Food();
String FoodName = FoodET.getText().toString().trim();
String calString = CalorieET.getText().toString().trim();
//convert the claories numbers to text
if (!calString.equals("")) {
int cal = Integer.parseInt(calString);
food.setFoodName(FoodName);
food.setCalories(cal);
//call addFood method from the DatabaseHandler
dba.addFood(food);
dba.close();
//clear the editTexts
FoodET.setText("");
CalorieET.setText("");
//take the user to the next screen
//
((appMain) getActivity()).loadSelection(0);
;
}
else
{
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SearchButton:
InputMethodManager inputManager = (InputMethodManager)
getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(
getActivity().getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
FoodSearch search = new FoodSearch(foodET,CalorieET );
search.execute();
break;
case R.id.SaveBtn:
foodET = FoodET.getText().toString();
calorieET=CalorieET.getText().toString();
if (FoodET.getText().toString().equals(null) ||
CalorieET.getText().toString().equals(null)||
CalorieET.getText().toString().equals("")){
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
}
((appMain) getActivity()).loadSelection(0);
break;
case R.id.CancelBtn:
// EditText descriptionET=
(EditText)getView().findViewById(R.id.foodEditText);
//descriptionET.setText("");
//EditText calorieET=
(EditText)getView().findViewById(R.id.caloriesEditText);
//calorieET.setText("");
((appMain) getActivity()).loadSelection(0);
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
private class FoodSearch extends AsyncTask<Void, Void, String> {
String food;
EditText calories;
FoodSearch(String food, EditText calories){
this.food = food;
this.calories = calories;
}
#Override
protected String doInBackground(Void... params) {
try {
food = food.replaceAll(" ", "%20");
URL url = new URL("http://api.nal.usda.gov/ndb/search/?
format=JSON&q=" + food
+"&max=1&offset=0&sort=r&api_
key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
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();
String result = stringBuilder.toString();
if(result.contains("zero results")) {
String s = "empty";
return s;
}
JSONObject object = (JSONObject) new
JSONTokener(result).nextValue();
JSONObject list = object.getJSONObject("list");
JSONArray items = list.getJSONArray("item");
String item = items.get(0).toString();
int i = item.indexOf("ndbno\":\"") + 8;
int f = item.indexOf("\"", i);
String ndbno = item.substring(i,f);
Log.d("DEBUG", ndbno);
URL url2 = new URL("http://api.nal.usda.gov/ndb/reports/?
ndbno="+ ndbno +"&type=b&format=JSON&api_
key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
HttpURLConnection urlConnection2 = (HttpURLConnection)
url2.openConnection();
BufferedReader bufferedReader2 = new BufferedReader(new
InputStreamReader(urlConnection2.getInputStream()));
StringBuilder stringBuilder2 = new StringBuilder();
String line2;
while ((line2 = bufferedReader2.readLine()) != null) {
stringBuilder2.append(line2).append("\n");
}
bufferedReader2.close();
String res = stringBuilder2.toString();
int index = res.indexOf("\"unit\": \"kcal\",") + 46;
int index2 = res.indexOf("\"", index);
String calories = res.substring(index,index2);
urlConnection2.disconnect();
return calories;
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
String s = "empty";
return s;
}
}
protected void onPostExecute(String response) {
if(!response.isEmpty() && !response.equals("empty")) {
calories.setText(response);
} else {
AlertDialog foodNotFound = new
AlertDialog.Builder(getContext()).create();
foodNotFound.setTitle("Error");
foodNotFound.setMessage("Food not found :(");
foodNotFound.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
dialog.dismiss();
}
});
}
}
}
}
You Can call the Async task within the same class and SHow alert dialog in the onPost execute section
public class AddEntry extends Fragment implements View.OnClickListener {
EditText DescriptionET,CalorieET; ImageButton Savebtn, Cancelbtn; Button searchbutton; String description , calorieAmt; //database
private DatabaseHandler dba;
public AddEntry() {
// Required empty public constructor
}
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { // Inflate the layout for this fragment View myView = inflater.inflate(R.layout.fragment_add_entry, container, false);
Savebtn = (ImageButton) myView.findViewById(R.id.SaveBtn);
Savebtn.setBackgroundColor(Color.TRANSPARENT);
Savebtn.setOnClickListener(this);
searchbutton = (Button) myView.findViewById(R.id.SearchButton);
searchbutton.setOnClickListener(this);
Cancelbtn = (ImageButton) myView.findViewById(R.id.CancelBtn);
Cancelbtn.setBackgroundColor(Color.TRANSPARENT);
Cancelbtn.setOnClickListener(this);
return myView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
DescriptionET= (EditText)view.findViewById(R.id.foodEditText);
DescriptionET.setInputType(InputType.TYPE_CLASS_TEXT);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
CalorieET.setInputType(InputType.TYPE_CLASS_NUMBER);
//save to database:
}
public void saveDataToDB (){
Food food = new Food();
String name = DescriptionET.getText().toString().trim();
String calString = CalorieET.getText().toString().trim();
//convert the claories numbers to text
if (!calString.equals("")) {
int cal = Integer.parseInt(calString);
food.setFoodName(name);
food.setCalories(cal);
//call addFood method from the DatabaseHandler
dba.addFood(food);
dba.close();
//clear the editTexts
DescriptionET.setText("");
CalorieET.setText("");
//take the user to the next screen
//
((appMain) getActivity()).loadSelection(0);
;
}
else
{
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SearchButton:
InputMethodManager inputManager = (InputMethodManager)
getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(
getActivity().getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
FoodSearch search = new FoodSearch(description,CalorieET);
search.execute();
break;
case R.id.SaveBtn:
description = DescriptionET.getText().toString();
calorieAmt=CalorieET.getText().toString();
if (DescriptionET.getText().toString().equals(null) ||
CalorieET.getText().toString().equals(null)||
CalorieET.getText().toString().equals("")){
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
}
((appMain) getActivity()).loadSelection(0);
break;
case R.id.CancelBtn:
// EditText descriptionET=
(EditText)getView().findViewById(R.id.foodEditText);
//descriptionET.setText("");
//EditText calorieET=
(EditText)getView().findViewById(R.id.caloriesEditText);
//calorieET.setText("");
((appMain) getActivity()).loadSelection(0);
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
private class FoodSearch extends AsyncTask<Void, Void, String>{
String food;
EditText calories;
FoodSearch(String food, EditText calories){
this.food = food;
this.calories = calories;
}
#Override
protected String doInBackground(Void... params) {
try {
food = food.replaceAll(" ", "%20");
URL url = new URL("http://api.nal.usda.gov/ndb/search/?
format=JSON&q=" + food +"&max=1&offset=0&sort=r&api_key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
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();
String result = stringBuilder.toString();
if(result.contains("zero results")) {
String s = "empty";
return s;
}
JSONObject object = (JSONObject) new
JSONTokener(result).nextValue();
JSONObject list = object.getJSONObject("list");
JSONArray items = list.getJSONArray("item");
String item = items.get(0).toString();
int i = item.indexOf("ndbno\":\"") + 8;
int f = item.indexOf("\"", i);
String ndbno = item.substring(i,f);
Log.d("DEBUG", ndbno);
URL url2 = new URL("http://api.nal.usda.gov/ndb/reports/?ndbno="+ ndbno +"&type=b&format=JSON&api_key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
HttpURLConnection urlConnection2 = (HttpURLConnection)
url2.openConnection();
BufferedReader bufferedReader2 = new BufferedReader(new
InputStreamReader(urlConnection2.getInputStream()));
StringBuilder stringBuilder2 = new StringBuilder();
String line2;
while ((line2 = bufferedReader2.readLine()) != null) {
stringBuilder2.append(line2).append("\n");
}
bufferedReader2.close();
String res = stringBuilder2.toString();
int index = res.indexOf("\"unit\": \"kcal\",") + 46;
int index2 = res.indexOf("\"", index);
String calories = res.substring(index,index2);
urlConnection2.disconnect();
return calories;
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
String s = "empty";
return s;
}
}
protected void onPostExecute(String response) {
if(!response.isEmpty() && !response.equals("empty")) {
calories.setText(response);
} else {
AlertDialog foodNotFound = new
AlertDialog.Builder(getContext()).create();
foodNotFound.setTitle("Error");
foodNotFound.setMessage("Food not found :(");
foodNotFound.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
}
}

App goes to MainActivity when running class

I am trying to run this script, but somewhere in doInBackground() it's being launched back to starting activity.
(What I'm trying to do is scan all available SSID's and check them in database)
Here is my code:
Button btnHit;
TextView txtJson;
private static final String TAG = "My Activity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_connection);
btnHit = (Button) findViewById(R.id.request);
txtJson = (TextView) findViewById(R.id.results);
if (Build.VERSION.SDK_INT > 22) {
final String CoarseLocation = Manifest.permission.ACCESS_COARSE_LOCATION;
final String AccessWifi = Manifest.permission.ACCESS_WIFI_STATE;
final String ChangeWifi = Manifest.permission.CHANGE_WIFI_STATE;
if (checkSelfPermission(CoarseLocation) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 123);
}
if (checkSelfPermission(AccessWifi) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.ACCESS_WIFI_STATE}, 123);
}
if (checkSelfPermission(ChangeWifi) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.CHANGE_WIFI_STATE}, 123);
}
}
LocationManager lman = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
boolean network_enabled = false;
try
{
network_enabled = lman.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {}
if (!network_enabled)
{
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
}
final WifiManager mWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
mWifiManager.setWifiEnabled(true);
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
List<ScanResult> results = mWifiManager.getScanResults();
final int Amount = results.size();
Log.v(TAG, "Wifi Scan Results Count: " + Amount);
int num = 0;
while (num < Amount)
{
Log.v(TAG, "SSID = " + results.get(num).SSID);
num = num+1;
}
int dis = 0;
String res = "Results:\n\n\n";
while (dis < Amount)
{
res = res + results.get(dis).SSID + "\n\n";
String surl = "http://myurl.com?ssid=" + results.get(dis).SSID;
new JsonTask().execute(surl);
dis = dis+1;
}
TextView textres = (TextView) findViewById(R. id. resnet);
textres.setText(res);
}
}, filter);
mWifiManager.startScan();
}
private class JsonTask extends AsyncTask<String, String, String> {
ProgressDialog pd;
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(FindConnection.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
if (line != "null")
{
Toast.makeText(getApplicationContext(), "Found one...", Toast.LENGTH_SHORT).show();
}
Log.d("Response: ", "> " + 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;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
}
}
And here's the error that I get:
11-12 19:48:56.920 21711-21811/com.comhet.comhet E/AndroidRuntime:
FATAL EXCEPTION: AsyncTask #1
Process: com.comhet.comhet, PID: 21711
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: Can't create handler inside thread
that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:362)
at android.widget.Toast.<init>(Toast.java:109)
at android.widget.Toast.makeText(Toast.java:276)
at com.comhet.comhet.FindConnection$JsonTask.doInBackground(FindConnection.java:194)
at com.comhet.comhet.FindConnection$JsonTask.doInBackground(FindConnection.java:156)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
at java.lang.Thread.run(Thread.java:818)
You are trying to show a Toast in the doInBackground() method of the AsyncTask. This is not allowed, as the doInBackground() method runs on a background thread and cannot perform actions related to the UI thread.
If you want to check the returned value, log the returned value or make the Toast inside the onPostExecute() method.
") Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()"
You can't create a Handler on a thread that hasn't called Looper.prepare. The main thread has that called for you. If you want to post to the main thread, you need to create than handler while on the main thread.
Have a look at your doInBackground method
You cannot do UI related operations in doInBackground.It should be done in onPostExecute{} method.
remove this from doInBackground:
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
if (line != "null")
{
Toast.makeText(getApplicationContext(), "Found one...", Toast.LENGTH_SHORT).show();
}
Log.d("Response: ", "> " + line);
}
}

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

I am using the following MainActivity, and I am still getting the following error message:
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:344)
at android.widget.Toast.<init>(Toast.java:100)
at android.widget.Toast.makeText(Toast.java:258)
at com.example.edtomach.whatstheweather.MainActivity$DownloadTask.doInBackground(MainActivity.java:114)
at com.example.edtomach.whatstheweather.MainActivity$DownloadTask.doInBackground(MainActivity.java:80)
Why am I getting this error? The relevant code is here:
public class MainActivity extends Activity {
EditText cityname;
TextView resulttextview;
public void findWeather(View view) {
Log.i("cityname", cityname.getText().toString());
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(cityname.getWindowToken(), 0);
try {
String encodedCityName = URLEncoder.encode(cityname.getText().toString(), "UTF-8");
DownloadTask task = new DownloadTask();
task.execute("http://api.openweathermap.org/data/2.5/weather?q=" + encodedCityName);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityname = (EditText) findViewById(R.id.cityname);
resulttextview = (TextView) findViewById(R.id.resulttextview);
}
public class DownloadTask 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 in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather content", weatherInfo);
JSONArray arr = new JSONArray(weatherInfo);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
String main = "";
String description = "";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
if (main != "" && description != "") {
message += main + ": " + description + "\r\n";
}
}
if (message != "") {
resulttextview.setText(message);
} else {
Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
do not put anything can modife the main thread on the doBackground methods which herited from asynctask process , in your case you put toast message when you catch exception :
Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();
instead that use logger message like e.g: Log.(TAG, "your message");

Categories

Resources