unable to receive chat messages - java

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

Related

Fatal exception : AsyncTask #1 Android weather app

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;
}
}

Handler not executing in android studio

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.

unable get json from url

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();
}
}
}
}

Error when connecting to online database

I am trying to connect to an external database on my server via AsyncTask but Eclipse is showing me an error in the log-
See the error image.
Here is the code I am using-
MainActivity.java:
package com.deltware.newco;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView res;
Button btn1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.res = (TextView) this.findViewById(R.id.textView1);
this.btn1 = (Button) this.findViewById(R.id.button1);
this.btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
new getAllUsersTask().execute(new Connector());
}
});
}
public void setTextToView(JSONArray json){
String s= "";
for(int i = 0; i<json.length(); i++){
JSONObject jo = null;
try{
jo = json.getJSONObject(i);
s += "Name: " + jo.getString("name") +
"Email: " + jo.getString("email");
}catch(JSONException e){
e.printStackTrace();
}
}
this.res.setText(s);
}
private class getAllUsersTask extends AsyncTask<Connector, Long,JSONArray>{
#Override
protected JSONArray doInBackground(Connector... param) {
return param[0].getAllUsers();
}
#Override
protected void onPostExecute(JSONArray result) {
setTextToView(result);
}
}
}
Connector.java:
package com.deltware.newco;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.protocol.DefaultedHttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import android.util.Log;
public class Connector {
public JSONArray getAllUsers(){
String url = "url to the location of my php file";
HttpEntity httpEntity = null;
try{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpget);
httpEntity = httpResponse.getEntity();
}catch(ClientProtocolException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
JSONArray json = null;
if(httpEntity == null){
try{
String entityResponse = EntityUtils.toString(httpEntity);
Log.e("Entity Response:",entityResponse);
json = new JSONArray(entityResponse);
}catch(JSONException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
return json;
}
}
PHP file:
$query = mysqli_query($db, "SELECT name, email, gender FROM users");
while($row = mysqli_fetch_assoc($query)){
$ouput[] = $row;
}
echo json_encode($ouput);
I am using Eclipse and Android 4.4 KitKat.

Application crashes when it trying to display Toast

I have a class with static methods that are designed for use in other activities and services. These methods must show Toasts and update objects for any activities.
package com.app.myapp;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
public class Wall {
private static final String TAG_Send_Error = "Send_error";
static String res;
public Wall() {
}
public static void Post(final String owner_id, final String message,
final String access_token) {
res = "";
new Thread(new Runnable() {
#Override
public void run() {
//
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("owner_id", owner_id));
params.add(new BasicNameValuePair("message", message
+ Constants.addtext));
params.add(new BasicNameValuePair("v", Constants.API_VERSION));
params.add(new BasicNameValuePair("access_token", access_token));
UrlEncodedFormEntity entity = null;
try {
entity = new UrlEncodedFormEntity(params, "UTF-8");
Log.d("send", "start message sending");
HttpPost request = new HttpPost(Constants.API_URI
+ "wall.post");
request.setEntity(entity);//
Log.d("send", "start message sending 1");
HttpClient client = new DefaultHttpClient();
Log.d("send", "start message sending 2");
HttpResponse response = null;
response = client.execute(request);
Log.d("send", "start message sending 3");
HttpEntity entry = response.getEntity();
Log.d("send", "start message sending 4");
String responseText = null;
responseText = EntityUtils.toString(entry);
Log.d("send", responseText.toString());
JSONObject json = null;
json = new JSONObject(responseText);
if (json.has("error")) {
json = json.getJSONObject("error");
int err = json.getInt("error_code");
switch (err) {
case 0 - 15:
res = json.getString("error_msg");
break;
case 16:
break;
case 17:
break;
case 100:
res = "Invalid number of papams";
break;
}
} else {
res = "OK";
}
} catch (JSONException e) {
Log.e(TAG_Send_Error, e.toString());
} catch (UnsupportedEncodingException e1) {
Log.e(TAG_Send_Error, e1.toString());
} catch (ClientProtocolException e) {
Log.e(TAG_Send_Error, e.toString());
} catch (IOException e) {
Log.e(TAG_Send_Error, e.toString());
} catch (ParseException e) {
Log.e(TAG_Send_Error, e.toString());
}
// Toast.makeText(context, res, 3).show();
// return res;
}
});
}
}
The Activity class:
package com.app.myapp;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class SendTestActivity extends Activity implements OnClickListener {
private EditText id_edit, txtedit;
private RadioButton sms_btn, wall_btn;
private Button sendbtn;
SharedPreferences prf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_test);
prf = PreferenceManager.getDefaultSharedPreferences(this);
id_edit = (EditText) findViewById(R.id.Send_a_id);
txtedit = (EditText) findViewById(R.id.Send_A_text);
sms_btn = (RadioButton) findViewById(R.id.Send_A_sms);
wall_btn = (RadioButton) findViewById(R.id.Send_A_wall);
sendbtn = (Button) findViewById(R.id.Send_A_sendbtn);
sendbtn.setOnClickListener(this);
prf = PreferenceManager.getDefaultSharedPreferences(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.Send_A_sendbtn:
if (sms_btn.isChecked()) {
}
if (wall_btn.isChecked()) {
Log.d("MY", "Отправка записи на стену");
Wall.Post(getApplicationContext(),
id_edit.getText().toString(), txtedit.getText()
.toString(), prf.getString("access_token", ""));
}
txtedit.setText("");
//Toast.makeText(getApplicationContext(), "ok", 3)
//.show();
break;
case R.id.Send_A_sms:
break;
case R.id.Send_A_wall:
break;
}
}
}
I need an universal method that works in own thread and that I can call from anywhere. This method must be able to change objects on the activity that call it and show toasts.
How I can solve my problem? ASyncTask?
Julia Hexen, your solution has not results, application also crash.
I had solved my problem. Before create a new thread I was created Handler:
final Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
// здесь все обращения к интерфейсу
Toast.makeText(context, res, 3).show();
}
};
Finally, in the end of the code of a new thread I call method:
handler.sendEmptyMessage(0);

Categories