I am having issue with this Weather App. Apparently there is some null string but I am just a beginner in android studio and I am not sure where. The app crashes and does not even load. The code is written in Java and is for Android mobile phone use.
Here is my Main Activity :
package com.example.theweatherapp;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.w3c.dom.Text;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.Date;
import Data.CityPreference;
import Data.JSONWeatherParser;
import Data.WeatherHttpClient;
import Model.Weather;
import Tool.Tools;
public class MainActivity extends AppCompatActivity {
private TextView cityName;
private TextView temp;
private ImageView iconView;
private TextView description;
private TextView humidity;
private TextView pressure;
private TextView wind;
private TextView sunrise;
private TextView sunset;
private TextView updated;
Weather weather = new Weather();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityName = (TextView) findViewById(R.id.mestoText);
iconView = (ImageView) findViewById(R.id.thumbnail);
temp = (TextView) findViewById(R.id.teplotaText);
description = (TextView) findViewById(R.id.mrakText);
humidity = (TextView) findViewById(R.id.vlhkostText);
pressure = (TextView) findViewById(R.id.tlakText);
wind = (TextView) findViewById(R.id.vitrText);
sunrise = (TextView) findViewById(R.id.SvitaniText);
sunset = (TextView) findViewById((R.id.SoumrakText));
updated = (TextView) findViewById(R.id.AktualizaceText);
CityPreference cityPreference = new CityPreference(MainActivity.this);
renderWeatherData(cityPreference.getCity());
}
public void renderWeatherData (String city)
{
WeatherTask weatherTask = new WeatherTask();
weatherTask.execute(new String[]{city + "&APPID=" + Tools.API_KEY + "&units=metric"});
}
private class DownloadImageAsyncTask extends AsyncTask<String, Void, Bitmap>
{
#Override
protected Bitmap doInBackground(String... params) {
return downloadImage(params[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
iconView.setImageBitmap(bitmap);
}
private Bitmap downloadImage(String code)
{
try {
URL url = new URL(Tools.ICON_URL + code + ".png");
Log.d("Data : ", url.toString());
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap currentBitmap = BitmapFactory.decodeStream(input);
return currentBitmap;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}
}
private class WeatherTask extends AsyncTask<String, Void, Weather>{
//check this wrong thread
#SuppressLint("WrongThread")
#Override
protected Weather doInBackground(String... params) {
String data = ( (new WeatherHttpClient().getWeatherData(params[0])));
weather = JSONWeatherParser.getWeather(data);
weather.iconData = weather.currentCondition.getIcon();
Log.v("Data: ", weather.currentCondition.getDescription());
new DownloadImageAsyncTask().execute(weather.iconData);
return weather;
}
#Override
protected void onPostExecute(Weather weather) {
super.onPostExecute(weather);
DateFormat dateFormat = DateFormat.getTimeInstance();
String sunriseDate = dateFormat.format(new Date(weather.location.getSunrise()));
String sunsetDate = dateFormat.format(new Date(weather.location.getSunset()));
String updateDate = dateFormat.format(new Date(weather.location.getLastupdate()));
DecimalFormat decimalFormat = new DecimalFormat("#.#");
String tempFormat = decimalFormat.format(weather.currentCondition.getTemperature());
cityName.setText(weather.location.getCity() + "," + weather.location.getCountry());
temp.setText("" + tempFormat + "°C");
humidity.setText("Vlhkost: " + weather.currentCondition.getHumidity() + "%");
pressure.setText("Tlak: " + weather.currentCondition.getPressure() + "hPa");
wind.setText("Vítr: " + weather.wind.getSpeed() + "mps");
sunrise.setText("Svítání: " + sunriseDate );
sunset.setText("Stmívání " + sunsetDate);
updated.setText("Naposledy aktualizováno: " + updateDate);
description.setText("Podmínky: " + weather.currentCondition.getCondition() + "(" + weather.currentCondition.getDescription()+")");
}
}
private void showInputDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Změnit město");
final EditText cityInput = new EditText(MainActivity.this);
cityInput.setInputType(InputType.TYPE_CLASS_TEXT);
cityInput.setHint("Brno,CZ");
builder.setView(cityInput);
builder.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
CityPreference cityPreference = new CityPreference(MainActivity.this);
cityPreference.setCity((cityInput.getText().toString()));
String newCity = cityPreference.getCity();
renderWeatherData(newCity);
}
});
builder.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id =item.getItemId();
if(id == R.id.change_mesto)
{
showInputDialog();
}
return super.onOptionsItemSelected(item);
}
}
And here is my JSONParser :
package Data;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import Model.Location;
import Model.Weather;
import Tool.Tools;
public class JSONWeatherParser {
public static Weather getWeather(String data){
Weather weather = new Weather();
try {
JSONObject jsonObject = new JSONObject(data);
Location place = new Location();
JSONObject coordObj = Tools.getObject("coord", jsonObject);
place.setLat(Tools.getFloat("lat",coordObj));
place.setLon(Tools.getFloat("lon",coordObj));
//sys
JSONObject sysObj = Tools.getObject("sys", jsonObject);
place.setCountry(Tools.getString("country", sysObj));
place.setLastupdate(Tools.getInt("dt", jsonObject));
place.setSunrise(Tools.getInt("sunrise", sysObj));
place.setSunset(Tools.getInt("sunset", sysObj));
place.setCity(Tools.getString("name", jsonObject));
weather.location = place;
//weather
JSONArray jsonArray = jsonObject.getJSONArray("weather");
JSONObject jsonWeather = jsonArray.getJSONObject(0);
weather.currentCondition.setWeatherId(Tools.getInt("id",jsonWeather));
weather.currentCondition.setDescription(Tools.getString("description",jsonWeather));
weather.currentCondition.setCondition(Tools.getString("main",jsonWeather));
weather.currentCondition.setIcon(Tools.getString("icon",jsonWeather));
JSONObject mainObj = Tools.getObject("main", jsonObject);
weather.currentCondition.setHumidity(Tools.getInt("humidity", mainObj));
weather.currentCondition.setPressure(Tools.getInt("pressure", mainObj));
weather.currentCondition.setMinTemp(Tools.getFloat("temp_min", mainObj));
weather.currentCondition.setMaxTemp(Tools.getFloat("temp_max", mainObj));
weather.currentCondition.setTemperature(Tools.getFloat("temp", mainObj));
JSONObject windObj = Tools.getObject("wind", jsonObject);
weather.wind.setSpeed(Tools.getFloat("speed",windObj));
weather.wind.setDeg(Tools.getFloat("deg",windObj));
JSONObject cloudObj = Tools.getObject("clouds", jsonObject);
weather.clouds.setPrecipitation(Tools.getInt("all",cloudObj));
return weather;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}
Error Log:
2019-12-11 11:12:03.183 8902-8949/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.theweatherapp, PID: 8902
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$4.done(AsyncTask.java:399)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
Caused by: 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:121)
at org.json.JSONTokener.nextValue(JSONTokener.java:98)
at org.json.JSONObject.<init>(JSONObject.java:164)
at org.json.JSONObject.<init>(JSONObject.java:181)
at Data.JSONWeatherParser.getWeather(JSONWeatherParser.java:16)
at com.example.theweatherapp.MainActivity$WeatherTask.doInBackground(MainActivity.java:131)
at com.example.theweatherapp.MainActivity$WeatherTask.doInBackground(MainActivity.java:123)
at android.os.AsyncTask$3.call(AsyncTask.java:378)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
EDIT:
Also adding my WeatherHttpClient code :
package Data;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.Buffer;
import Tool.Tools;
public class WeatherHttpClient {
public String getWeatherData(String place) {
HttpURLConnection connection = null;
InputStream inputStream = null;
try {
connection =(HttpURLConnection) (new URL(Tools.BASE_URL + place + "&APPID="+ Tools.API_KEY)).openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoInput(true);
connection.connect();
//read the response
StringBuffer stringBuffer = new StringBuffer();
inputStream=connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while ((line = bufferedReader.readLine())!=null){
stringBuffer.append(line + "\r\n");
}
inputStream.close();
connection.disconnect();
return stringBuffer.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Related
I am trying to build an app for class and am having trouble with handling data that is gathered in another thread. The data does not seems to being passed through the handlers handleMessage method.
This is my main activity
import android.content.Context;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
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.EditText;
import android.widget.FrameLayout;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.Buffer;
import java.util.*;
public class MainActivity extends AppCompatActivity implements BookListFragment.OnFragmentInteractionListener {
ArrayList<Book> names;
private boolean twoPane = false;
BookListFragment blf;
BookDetailsFragment bdf;
// Handler bookHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
twoPane = findViewById(R.id.container2) == null;
names = new ArrayList<Book>();
final EditText searchBar = findViewById(R.id.searchbar);
final Handler bookHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
String response = (String) msg.obj;
try{
JSONArray tmp = new JSONArray(response);
for(int i = 0; i < tmp.length(); i++){
JSONObject a = tmp.getJSONObject(i);
int id = a.getInt("book_id");
String title = a.getString("title");
Log.d("BOOK_id", a.getInt("book_id")+"");
String author = a.getString("author");
int published = a.getInt("published");
String coverUrl = a.getString("cover_url");
Book book = new Book(id,title,author,published,coverUrl);
names.add(book);
}
} catch (Exception e){
Log.d("FAIL", e.toString());
}
return false;
}
});
Thread t = new Thread(){
#Override
public void run() {
String searchString = searchBar.getText().toString();
URL bookURL;
try {
bookURL = new URL("https://kamorris.com/lab/audlib/booksearch.php?search="+searchString);
BufferedReader reader = new BufferedReader(new InputStreamReader(bookURL.openStream()));
String response = "",tmpResponse;
tmpResponse = reader.readLine();
while(tmpResponse != null){
response = response + tmpResponse;
tmpResponse = reader.readLine();
}
Log.d("Handler", response);
Message msg = Message.obtain();
msg.obj = response;
bookHandler.handleMessage(msg);
} catch (Exception e) {
Log.e("Fail", e.toString());
}
}
};
t.start();
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread t = new Thread(){
#Override
public void run() {
String searchString = searchBar.getText().toString();
URL bookURL;
try {
bookURL = new URL("https://kamorris.com/lab/audlib/booksearch.php?search="+searchString);
BufferedReader reader = new BufferedReader(new InputStreamReader(bookURL.openStream()));
String response = "",tmpResponse;
tmpResponse = reader.readLine();
while(tmpResponse != null){
response = response + tmpResponse;
tmpResponse = reader.readLine();
}
JSONArray bookOBJ= new JSONArray(response);
Message msg = Message.obtain();
msg.obj = bookOBJ;
bookHandler.handleMessage(msg);
} catch (Exception e) {
Log.d("Fail", e.toString());
}
}
};
t.start();
}
});
}
The code is suppose to get data from an api and then in the handleMessage method it is suppose to parse the data into a book object that contains two int and three string variables. The problem is that the handler never executes any code.
The execution should be that the debugger log should have the response string with the data from the API and then the id of every book in the JSON file, but it only has the data from the api displayed.
I am trying to send an image and some string values from android to a php script using HttpURLConnection. I have successfully done so with strings, but can't seem to get it right with the image. I am using Base64 (android.util.Base64) to convert my image to a string to send it. Now, I have a separate HttpParse.java file I use to send all my info to the server, and I think that is where the change needs to be made to allow the image, but I'm not sure, (I am newer to java/android development). I've researched several similar questions, but they aren't fully clicking for me for what I'm doing wrong. Also, I have tested that I am successfully converting the image to a string. Here is my code:
EDIT I got a little farther... After testing, I am getting the issue because the three variables I try to get with getArguments() are coming back as null... But, I can't figure out how to get them to come through successfully... I added the code for how I start my fragment and how I try to get my bundle
My fragment start:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_units);
Intent intent = getIntent();
LexaUser = intent.getStringExtra("UserName");
ReadOnly = intent.getStringExtra("ReadOnly");
Password = intent.getStringExtra("Password");
QA = intent.getStringExtra("QA");
SearchValue = intent.getStringExtra("SearchInput");
bottomNavigation = (BottomNavigationView)findViewById(R.id.bottom_navigation);
bottomNavigation.inflateMenu(R.menu.bottom_menu);
fragmentManager = getSupportFragmentManager();
bottomNavigation.getMenu().getItem(0).setChecked(true);
UnitDetailsHeader = findViewById(R.id.UnitDetailsViewTitle);
UnitDetailsHeader.setText(SearchValue);
UnitSizeText = findViewById(R.id.UnitSize);
UnitStatusText = findViewById(R.id.UnitStatus);
if (SearchValue.contains("-")) {
getUnitDetails(SearchValue, LexaUser);
} else {
getSiblings();
}
bottomNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.action_search:
fragment = new NewUnitStatusFragment();
break;
case R.id.action_cart:
fragment = new PendingUnitStatusFragment();
break;
case R.id.action_hot_deals:
fragment = new FinalUnitStatusFragment();
break;
case R.id.action_siblings:
fragment = new SiblingUnitFragment();
break;
}
Bundle connBundle = new Bundle();
connBundle.putString("SearchValue", SearchValue);
connBundle.putString("LexaUser", LexaUser);
connBundle.putString("Password", Password);
connBundle.putString("QA", QA);
fragment.setArguments(connBundle);
final FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_container, fragment).commit();
return true;
}
});
}
And where I try to get my arguments: (I originally had in onCreateView but then tried to move it to onCreate. But the behavior was the same)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
SearchValue = getArguments().getString("SearchValue");
LexaUser = getArguments().getString("LexaUser");
Password = getArguments().getString("Password");
}
}
My fragment where I get the image and send my data:
package [my_package];
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import android.util.Base64;
import java.util.HashMap;
import static android.app.Activity.RESULT_OK;
public class NewUnitStatusFragment extends Fragment {
Context newUnitStatusContext;
Activity newUnitStatusActivity;
Intent cameraIntent;
ProgressDialog progressDialog;
String ReadOnly;
String LexaUser;
String Password;
String SearchValue;
String finalResultNewUnitStatus;
String HttpURLNewUnitStatus = "https://[path/to/file]/insertNewUnitStatus.php";
HashMap<String, String> hashMapNewUnitStatus = new HashMap<>();
HttpParse httpParse = new HttpParse();
Spinner statusSpinner;
Spinner generalCauseSpinner;
EditText newUSComment;
Button addPhotoBtn;
ImageView newUnitStatusImage;
Button addNewUnitStatus;
String newUnitStatus;
String generalCause;
String newUnitStatusComment;
String newUnitStatusPhoto;
String message;
private static final int PICK_FROM_GALLERY = 1;
public NewUnitStatusFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_newunitstatus, container, false);
newUnitStatusContext = getContext();
newUnitStatusActivity = getActivity();
statusSpinner = view.findViewById(R.id.Status);
generalCauseSpinner = view.findViewById(R.id.GeneralCause);
newUSComment = view.findViewById(R.id.NewComment);
newUnitStatusImage = view.findViewById(R.id.AddPhoto);
addPhotoBtn = view.findViewById(R.id.AddPhotosLabel);
addNewUnitStatus = view.findViewById(R.id.addBtnNewUnitStatus);
ArrayAdapter<CharSequence> statusSpinnerAdapter = ArrayAdapter.createFromResource(newUnitStatusContext,
R.array.new_unit_status_array, android.R.layout.simple_spinner_item);
statusSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
statusSpinner.setAdapter(statusSpinnerAdapter);
newUnitStatus = statusSpinner.getSelectedItem().toString();
ArrayAdapter<CharSequence> generalCauseSpinnerAdapter = ArrayAdapter.createFromResource(newUnitStatusContext,
R.array.status_general_cause_array, android.R.layout.simple_spinner_item);
generalCauseSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
generalCauseSpinner.setAdapter(generalCauseSpinnerAdapter);
generalCause = generalCauseSpinner.getSelectedItem().toString();
addPhotoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startGallery();
}
});
// Set a click listener for the text view
addNewUnitStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
newUnitStatus = statusSpinner.toString();
generalCause = generalCauseSpinner.toString();
newUnitStatusComment = newUSComment.toString();
if (getArguments() != null) {
SearchValue = getArguments().getString("SearchValue");
LexaUser = getArguments().getString("LexaUser");
Password = getArguments().getString("Password");
}
addNewUnitStatus(SearchValue, newUnitStatus, generalCause, newUnitStatusComment, newUnitStatusPhoto, LexaUser, Password);
}
});
return view;
}
private void startGallery() {
cameraIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
cameraIntent.setType("image/*");
cameraIntent.setAction(Intent.ACTION_GET_CONTENT);
if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(cameraIntent, 1000);
} else {
Toast.makeText(newUnitStatusContext, "Error: " + cameraIntent + " - cameraIntent.resolveActivity(getActivity().getPackageManager()) = null", Toast.LENGTH_LONG).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//super method removed
if (resultCode == RESULT_OK) {
if (requestCode == 1000) {
Uri returnUri = data.getData();
try {
Bitmap bitmapImage = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), returnUri);
newUnitStatusImage.setImageBitmap(bitmapImage);
newUnitStatusImage.buildDrawingCache();
Bitmap bm = newUnitStatusImage.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
newUnitStatusPhoto = Base64.encodeToString(b, Base64.DEFAULT);
} catch (IOException ioEx) {
ioEx.printStackTrace();
Toast.makeText(newUnitStatusContext, "ioEx Error: " + ioEx, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(newUnitStatusContext, "Error: " + requestCode, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(newUnitStatusContext, "Error: " + resultCode, Toast.LENGTH_LONG).show();
}
}
public void addNewUnitStatus(String searchInput, String newUnitStatus, String generalCause, String newUnitStatusComment, String newUnitStatusPhoto, String lexaUser, String password) {
class NewUnitStatusClass extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(newUnitStatusContext, "Loading Data", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
if (httpResponseMsg != null) {
try {
JSONObject object = new JSONObject(httpResponseMsg);
message = object.getString("message");
Toast.makeText(newUnitStatusContext, httpResponseMsg, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
Toast.makeText(newUnitStatusContext, "Error: " + e.toString(), Toast.LENGTH_LONG).show();
} // catch (JSONException e)
progressDialog.dismiss();
} else {
progressDialog.dismiss();
Toast.makeText(newUnitStatusContext, "HttpResponseMsg is null.", Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
hashMapNewUnitStatus.put("searchinput", params[0]);
hashMapNewUnitStatus.put("newUnitStatus", params[1]);
hashMapNewUnitStatus.put("generalCause", params[2]);
hashMapNewUnitStatus.put("newUnitStatusComment", params[3]);
hashMapNewUnitStatus.put("newUnitStatusPhoto", params[4]);
hashMapNewUnitStatus.put("lexauser", params[5]);
hashMapNewUnitStatus.put("password", params[6]);
finalResultNewUnitStatus = httpParse.postRequest(hashMapNewUnitStatus, HttpURLNewUnitStatus);
return finalResultNewUnitStatus;
}
}
NewUnitStatusClass newUnitStatusClass = new NewUnitStatusClass();
newUnitStatusClass.execute(searchInput, newUnitStatus, generalCause, newUnitStatusComment, newUnitStatusPhoto, lexaUser, password);
}
}
And my code to do that actuall HttpURLConnection: HttpParse.java
package [my_package];
import android.app.ListActivity;
import android.widget.ArrayAdapter;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class HttpParse extends ListActivity {
String FinalHttpData = "";
String Result;
BufferedWriter bufferedWriter;
OutputStream outputStream;
BufferedReader bufferedReader;
StringBuilder stringBuilder = new StringBuilder();
URL url;
public String postRequest(HashMap<String, String> Data, String HttpUrlHolder) {
try {
url = new URL(HttpUrlHolder);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(14000);
httpURLConnection.setConnectTimeout(14000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
outputStream = httpURLConnection.getOutputStream();
bufferedWriter = new BufferedWriter(
new OutputStreamWriter(outputStream, "UTF-8"));
bufferedWriter.write(FinalDataParse(Data));
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
bufferedReader = new BufferedReader(
new InputStreamReader(
httpURLConnection.getInputStream()
)
);
FinalHttpData = bufferedReader.readLine();
}
else {
FinalHttpData = "Something Went Wrong";
}
} catch (Exception e) {
e.printStackTrace();
}
return FinalHttpData;
}
public String FinalDataParse(HashMap<String,String> hashMap2) throws UnsupportedEncodingException {
for(Map.Entry<String,String> map_entry : hashMap2.entrySet()){
stringBuilder.append("&");
stringBuilder.append(URLEncoder.encode(map_entry.getKey(), "UTF-8"));
stringBuilder.append("=");
stringBuilder.append(URLEncoder.encode(map_entry.getValue(), "UTF-8"));
}
Result = stringBuilder.toString();
return Result ;
}
}
All help is appreciated! Thank you!
P.S. my app shows the following error:
W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
This then leads to this:
E/JSONException: Error: org.json.JSONException: End of input at character 0 of
I'm relatively new to Android app development and wonder what I'm doing wrong. I have an AsyncTask that connects to my web server with username and password and returns the user dataset as json object. Unfortunately I can't get the json string, because onPostExecute() in my AsyncHttpReading class doesn't seem to get called. Why?
MainActivity.java
package com.alphavoice.sampleproject;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import com.alphavoice.sampleproject.community.user.User;
import com.alphavoice.sampleproject.util.HttpReader;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean isLoggedIn = (appPrefs.getInt("userId", 0) != 0) ? true : false;
if (isLoggedIn) {
renderCommunityView();
}
else {
setContentView(R.layout.activity_main);
final Button btnLogin = (Button) findViewById(R.id.btn_login);
final EditText etUsername = (EditText) findViewById(R.id.et_username);
final EditText etPassword = (EditText) findViewById(R.id.et_password);
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
String loginUrl = "http://example.com/websrv/get_user.php?username=" + username + "&password=" + password;
AsyncHttpReading httpReading = new AsyncHttpReading();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
int corePoolSize = 60;
int maximumPoolSize = 80;
int keepAliveTime = 10;
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>(maximumPoolSize);
Executor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, workQueue);
// httpReading.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, loginUrl);
httpReading.executeOnExecutor(threadPoolExecutor, loginUrl);
}
else {
httpReading.execute(loginUrl);
}
if (httpReading.getLoggedInUser() != null) {
// renderCommunityView();
btnLogin.setBackgroundColor(Color.GREEN);
}
else {
// wrong combination of username & password => try again
etUsername.setBackgroundColor(Color.rgb(255, 204, 204));
etPassword.setBackgroundColor(Color.rgb(255, 204, 204));
}
}
});
}
}
private void renderCommunityView() {
setContentView(R.layout.activity_community);
}
private class AsyncHttpReading extends AsyncTask<String, Void, String> {
private String response = "";
private User loggedInUser = null;
public AsyncHttpReading() { }
public String getResponse() {
return response;
}
public User getLoggedInUser() {
return loggedInUser;
}
#Override
protected String doInBackground(String... urls) {
HttpReader httpReader = new HttpReader(urls[0]);
response = httpReader.getResponse();
return response;
}
#Override
protected void onPostExecute(String response) {
try {
JSONObject userData = new JSONObject(this.getResponse()).getJSONObject("0");
if (userData != null) {
loggedInUser = new User(userData);
}
} catch (JSONException e) {
Log.e("SAMPLEPROJECT", "Could not parse json data!");
}
}
}
}
HttpReader.java
package com.alphavoice.sampleproject.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import android.util.Log;
public class HttpReader {
private String url = "";
public HttpReader(String url) {
this.url = url;
}
public String getURL() {
return url;
}
public String getResponse() {
URL urlObj = null;
HttpURLConnection connection = null;
// http request
try {
urlObj = new URL(url);
connection = (HttpURLConnection) urlObj.openConnection();
connection.setReadTimeout(10000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
} catch (Exception e) {
Log.e("SAMPLEPROJECT", "Could not connect to web server!");
}
// read stream
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(urlObj.openStream()));
StringBuffer buffer = new StringBuffer();
char[] chars = new char[1024];
int read = 0;
while ((read = reader.read(chars)) != -1) {
buffer.append(chars, 0, read);
}
reader.close();
return buffer.toString();
} catch (IOException e) {
Log.e("SAMPLEPROJECT", "Could not open stream!");
}
return null;
}
}
User.java
package com.alphavoice.sampleproject.community.user;
import org.json.JSONObject;
public class User {
public User(JSONObject dataset) {
}
}
i have to create simple login page where after entering username and password we click to submit button. when we click on submit button then it goes to server and check the username and other information if the info matches then it moves to next activity otherwise nothing will happen . below is my code . i dont know how to do after getting response from the server.
package com.example.dev_1.myapplication;
import android.app.DownloadManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.net.Uri
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.ref.ReferenceQueue;
import java.net.HttpURLConnection;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.sql.Connection;
public class MainActivity extends AppCompatActivity {
Button button;
String connectionString, params;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText username = (EditText) findViewById(R.id.editText);
final EditText password = (EditText) findViewById(R.id.editText2);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.button1) {
String userNameString = username.getText().toString();
String passwordString = password.getText().toString();
String url = "http://122.160.78.189:82/androidserver/LoginSalesPerson";
String params = null;
try {
params = "user=" + URLEncoder.encode(userNameString, "UTF-8") + "&password=" + URLEncoder.encode(passwordString, "UTF-8") + "&appVersion=1.26";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
JSONArray dataJsonArr = null;
new Mytask().execute(url, params);
}
}
}));
}
private void checkLogin(String result) throws JSONException {
String url = "http://122.160.78.189:82/androidserver/LoginSalesPerson";
JSONArray user = null;
try{
// Creating new JSON Parser
///JSONParser jParser = new JSONParser();
// Getting JSON from URL
// JSONObject json = jParser.getJSONFromUrl(url);
if (result != null)
{
//JSONObject emp=(new JSONObject(url).getJSONObject("username"));
JSONObject emp = new JSONObject(result.toString());
String username=emp.getString("userName");
//String empspassword=emp.getString("password");
String str="username:"+username;
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
intent.putExtra("username", str);
startActivity(intent);}
}catch (Exception e) {
e.printStackTrace();
}
}
// EditText usernameString = (EditText) findViewById(R.id.editText);
// String str = usernameString.getText().toString();
// if (sharedPreferences.equals(str)) {
// Intent intent = new Intent(MainActivity.this, Main2Activity.class);
// intent.putExtra("username", str);
//startActivity(intent);
// To retrieve value from shared preference in another activity
// sharedPreferences = getApplicationContext().getSharedPreferences(
// "sharedPrefName", 0);
// id = sharedPreferences.getString("key_name", "defaultvalue");
class Mytask extends AsyncTask<String, Void, String> {
// Runs in UI before background thread is called
#Override
protected void onPreExecute() {
setProgressBarVisibility(true);
// Do something like display a progress bar
}
// This is run in a background thread
#Override
protected String doInBackground(String... params) {
return getFromServer(params[0], params[1]);
}
// This runs in UI when background thread finishes
#Override
protected void onPostExecute(String result) {
try {
checkLogin(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
public String getFromServer(String connectionString, String params) {
String response = "";
try {
// android.os.Debug.waitForDebugger();
URL url = new URL(connectionString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(10 * 1000); //10 Seconds
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length));
con.setRequestProperty("Content-Language", "en-US");
con.setUseCaches(false);
con.setDoInput(true);
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
InputStream is = con.getInputStream();
response = read(is);
} catch (Exception e) {
e.printStackTrace();
} finally {
return response;
}
}
private String read(InputStream in) {
BufferedReader reader;
StringBuilder response = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
return response.toString();
}
}
}
}
I have problem and need help when receive messages for the chat i make, i only success to send the messages and show the messages that i send, but i failed to receive and show the messages that i receive from other party.
I can't retrieve the messages from database and always null, when the messages come the code not checking there is any messages and null and i think it's stop.
and I checking the stream, the stream can't get the content.
i don't understand what's wrong, so anyone please help me. thank you
chatroom.php
<?php
include "config.php";
$idu= $_REQUEST['idu'];
$idch= $_REQUEST['idch'];
if($idu && $idch){
$sqlString = " SELECT a.id, a.message, a.system, b.id, b.name, b.course, c.id, d.firstname FROM mdl_chat_messages
as a inner join mdl_chat as b on b.name=a.chatid inner join mdl_course as c on c.id=b.course
inner join mdl_user as d on d.id=a.userid and a.system = 0 and a.userid='".$_GET['idu']."'
and a.chatid='".$_GET['idch']."' and a.id='".$_GET['idcm']."'";}
$res = mysql_query($sqlString);
if(mysql_num_rows($res)>0)
{
while($data = mysql_fetch_array($res))
{
$msg = $data["message"];
echo "$msg";
}
}
?>
Chatroom.java
package mobile.chat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.http.client.ClientProtocolException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import mobile.config.CourseHttpClient;
import mobile.config.Koneksi;
import com.karismaelearning.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
/*import android.util.Log;*/
/*import android.os.Handler;*/
import android.view.*;
import android.widget.*;
public class ChatRoom extends Activity {
public Koneksi linkurl;
String SERVER_URL;
private EditText messageText;
private TextView meLabel;
private TextView friendLabel;
private ViewGroup messagesContainer;
private ScrollView scrollContainer;
/* private Handler handler = new Handler();*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatpage);
messagesContainer = (ViewGroup) findViewById(R.id.messagesContainer);
scrollContainer = (ScrollView) findViewById(R.id.scrollContainer);
Button sendMessageButton = (Button) findViewById(R.id.sendButton);
Bundle bundle = this.getIntent().getExtras();
final String paramnama = bundle.getString("nama");
messageText = (EditText) findViewById(R.id.messageEdit);
meLabel = (TextView) findViewById(R.id.meLabel);
friendLabel = (TextView) findViewById(R.id.friendLabel);
meLabel.setText(paramnama + " (me)");
final String param1 = bundle.getString("keyCourseId");
final String param2 = bundle.getString("keyUserId");
final String param3 = bundle.getString("keyChatsId");
final String param4 = bundle.getString("keyMessagesId");
receiveMsg();
sendMessageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("messages", messageText.getText().toString()));
String response = null;
try {
linkurl = new Koneksi(ChatRoom.this);
SERVER_URL = linkurl.getUrl();
SERVER_URL += "/mobile/ChatKirimTeks.php?idu="+param2+"&idch="+param3;
response = CourseHttpClient.executeHttpPost(SERVER_URL, postParameters);
String res = response.toString();
res = res.trim();
res = res.replaceAll("\\s+","");
if(res.equals("1")){
String messageString = messageText.getText().toString();
showMessage(messageString, true);
messageText.getText().clear();
}else
{
createDialog("Maaf", "Messages Anda Gagal Terkirim");
}
}
catch (Exception e) {
messageText.setText(e.toString());
}
}
});}
HttpURLConnection connection;
URL url = null;
try{
linkurl = new Koneksi(this);
SERVER_URL = linkurl.getUrl();
SERVER_URL += "/mobile/ChatRoom.php?idu="+param2+"&idch="+param3+"&idcm="+param4;
url = new URL(SERVER_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(SERVER_URL);
//ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
//add parameter
//httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpRespose = httpClient.execute(httpPost);
HttpEntity httpEntity = httpRespose.getEntity();
//read content
InputStream in = httpEntity.getContent();
BufferedReader read = new BufferedReader(new InputStreamReader(in));
String msg = "";
while(true)
{
try {
msg = read.readLine();
Log.d("","MSGGG: "+ msg);
//msgList.add(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.getMessage();
}
if(msg == null)
{
break;
}
else
{
showMessage(msg, false);
}
}}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void showMessage(String message, boolean leftSide) {
final TextView textView = new TextView(ChatRoom.this);
textView.setTextColor(Color.BLACK);
textView.setText(message);
int bgRes = R.drawable.left_message_bg;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
if (!leftSide) {
bgRes = R.drawable.right_message_bg;
params.gravity = Gravity.RIGHT;
}
textView.setLayoutParams(params);
textView.setBackgroundResource(bgRes);
runOnUiThread(new Runnable() {
#Override
public void run() {
messagesContainer.addView(textView);
// Scroll to bottom
if (scrollContainer.getChildAt(0) != null) {
scrollContainer.scrollTo(scrollContainer.getScrollX(), scrollContainer.getChildAt(0).getHeight());
}
scrollContainer.fullScroll(View.FOCUS_DOWN);
}
});
}
private void createDialog(String title, String text) {
AlertDialog ad = new AlertDialog.Builder(this)
.setPositiveButton("Ok", null)
.setTitle(title)
.setMessage(text)
.create();
ad.show();
}
}
LogCat
06-04 17:42:55.932: I/ActivityManager(61): Starting: Intent { cmp=com.karismaelearning/mobile.chat.ChatDetail (has extras) } from pid 410
06-04 17:42:56.762: I/ActivityManager(61): Displayed com.karismaelearning/mobile.chat.ChatDetail: +816ms
06-04 17:42:57.392: I/ActivityManager(61): Starting: Intent { cmp=com.karismaelearning/mobile.chat.ChatRoom (has extras) } from pid 410
06-04 17:42:57.802: D/(410): MSGGG: null
06-04 17:42:58.334: I/ActivityManager(61): Displayed com.karismaelearning/mobile.chat.ChatRoom: +862ms