I am trying to get an image from my data base and insert it using imageView in android
my php code:
<?php
if(isset($_POST["IdToSearch"]) && $_POST["IdToSearch"] != "") {
$firstid = $_POST["IdToSearch"];
$con = mysqli_connect("localhost","root","","bdUniv");
if(mysqli_connect_errno()) {
echo'Database connection error: '. mysqli_connect_error();
exit();
}
$firstid = mysqli_real_escape_string($con,$firstid);
$userdetails = mysqli_query($con,"SELECT * FROM Etudiant WHERE id = '$firstid'");
if(!$userdetails) {
echo'Couldnotrunquery: '. mysqli_error($con);
exit();
}
$row = mysqli_fetch_row($userdetails);
$result_data = array(
'id' => $row[0],
'nom' => $row[1],
'prenom' => $row[2],
'age' => $row[3],
'photo' => $row[4],
);
echo json_encode($result_data);
}else{
echo"Could not complete query. Missingparameter";
}
?>
My java code:
package com.example.getdatafrombdd;
import java.io.File;
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.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity_GET extends Activity {
Button buttonGetData = null;
EditText editTextSearchString = null;
TextView textViewId = null;
TextView textViewNom = null;
TextView textViewPrenom = null;
TextView textViewAge = null;
ImageView imgViewPhoto = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity_get);
buttonGetData = (Button) findViewById(R.id.buttonGetData);
editTextSearchString = (EditText) findViewById(R.id.editTextSearchString);
textViewId = (TextView) findViewById(R.id.txtId);
textViewNom = (TextView) findViewById(R.id.txtNom);
textViewPrenom = (TextView) findViewById(R.id.txtPrenom);
textViewAge = (TextView) findViewById(R.id.txtAge);
imgViewPhoto = (ImageView) findViewById(R.id.imgPhoto);
//Setup the Button's OnClickListener
buttonGetData.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Get the data
DoPOST mDoPOST = new DoPOST(MainActivity_GET.this, editTextSearchString.getText().toString());
mDoPOST.execute("");
buttonGetData.setEnabled(false);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity__get, menu);
return true;
}
public class DoPOST extends AsyncTask<String, Void, Boolean> {
// String: le type des paramètres fournis à la tâche.
// Void: le type de données transmises durant la progression du traitement.
// Boolean: le type du résultat de la tâche.
Context mContext = null;
String IdToSearch = "";
//Result data
int intId;
String strNom;
String strPrenom;
int intAge;
String strPictPath;
Exception exception = null;
DoPOST(Context context, String nameToSearch) {
mContext = context;
IdToSearch = nameToSearch;
}
#Override
protected Boolean doInBackground(String... arg0) {
try{
//Setup the parameters
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// key value
nameValuePairs.add(new BasicNameValuePair("IdToSearch", IdToSearch));
//Add more parameters as necessary
//Create the HTTP request
HttpParams httpParameters = new BasicHttpParams();
//Setup timeouts
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost("http://10.0.2.2/univ/getFromUniv.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);
//Retrieve the data from the JSON object
intId = jsonObject.getInt("id");
strNom = jsonObject.getString("nom");
strPrenom = jsonObject.getString("prenom");
intAge = jsonObject.getInt("age");
strPictPath = jsonObject.getString("photo");
}catch (Exception e){
Log.e("ClientServerDemo", "Error:", e);
exception = e;
}
return true;
}
#Override
protected void onPostExecute(Boolean valid){
//Update the UI
textViewId.setText("Id: " + intId);
textViewNom.setText("Nom: " + strNom);
textViewPrenom.setText("Prenom: " + strPrenom);
textViewAge.setText("Age: " + intAge);
File imgFile = new File(strPictPath);
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imgViewPhoto.setImageBitmap(myBitmap);
buttonGetData.setEnabled(true);
if(exception != null){
Toast.makeText(mContext, exception.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
When i compiled it i get the: id, name, 2nd name, age but no image found!
And the error is:
1-06 20:19:17.527: E/BitmapFactory(786): Unable to decode stream: java.io.FileNotFoundException: /home/user/images/myPict.jpg: open failed: ENOENT (No such file or directory)
Help please!
You are doing this very wrong. Your server is returning the path of the photo on the server, not in the app. When you go to open the file, your app gives you an error because the file is not found locally, which is where your app is looking. To fix this, you should either download the photo from the server in your AsyncTask or store the Internet path of your picture and use a library like Picasso to download the image at that path to the ImageView.
EDIT:
As #Zerkz noted in his comment, you could also pass the image contents itself in your JSON by encoding them in base64 and then decoding those contents to a Bitmap in your AsyncTask. This would be advantageous if you don't plan on publicly exposing the URL to any of your images or if they will eventually be stored in a database.
Related
I found this old android example code that can filter tweets from Twitter's live streaming API according to the input of user, but the problem is that it uses the basic authorization.
Obviously it wouldn't work and I got the "401 unauthorized" error.
Here is the original code:
package com.teleknesis.android.twitter.livestream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class TwitterLiveStreamingActivity extends Activity {
private List<HashMap<String,String>> mTweets = new ArrayList<HashMap<String,String>>();
private SimpleAdapter mAdapter;
private boolean mKeepRunning = false;
private String mSearchTerm = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mAdapter = new SimpleAdapter(this, mTweets, android.R.layout.simple_list_item_2, new String[] {"Tweet", "From"}, new int[] {android.R.id.text1, android.R.id.text2});
((ListView)findViewById(R.id.Tweets)).setAdapter(mAdapter);
}
public void startStop( View v ) {
if( ((Button)v).getText().equals("Start") ) {
mSearchTerm = ((EditText)findViewById(R.id.SearchText)).getText().toString();
if( mSearchTerm.length() > 0 ) {
new StreamTask().execute();
mKeepRunning = true;
((Button)v).setText("Stop");
}
else {
Toast.makeText(this, "You must fill in a search term", Toast.LENGTH_SHORT).show();
}
}
else {
mKeepRunning = false;
((Button)v).setText("Start");
}
}
private class StreamTask extends AsyncTask<Integer, Integer, Integer> {
private String mUrl = "https://stream.twitter.com/1/statuses/filter.json?track=";
#Override
protected Integer doInBackground(Integer... params) {
try {
DefaultHttpClient client = new DefaultHttpClient();
Credentials creds = new UsernamePasswordCredentials("username", "password");
client.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
HttpGet request = new HttpGet();
request.setURI(new URI("https://stream.twitter.com/1/statuses/filter.json?track=" + mSearchTerm));
HttpResponse response = client.execute(request);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader( new InputStreamReader(in) );
parseTweets(reader);
in.close();
}
catch (Exception e) {
Log.e("Twitter", "doInBackground_" + e.toString());
}
return new Integer(1);
}
private void parseTweets( BufferedReader reader ) {
try {
String line = "";
do {
line = reader.readLine();
Log.d("Twitter", "Keep Running: " + mKeepRunning
+ " Line: " + line);
JSONObject tweet = new JSONObject(line);
HashMap<String, String> tweetMap = new HashMap<String, String>();
if (tweet.has("text")) {
tweetMap.put("Tweet", tweet.getString("text"));
tweetMap.put("From", tweet.getJSONObject("user")
.getString("screen_name"));
mTweets.add(0, tweetMap);
if (mTweets.size() > 10) {
mTweets.remove(mTweets.size() - 1);
}
//mAdapter.notifyDataSetChanged();
publishProgress(1);
}
} while (mKeepRunning && line.length() > 0);
}
catch (Exception e) {
// TODO: handle exception
}
}
protected void onProgressUpdate(Integer... progress) {
mAdapter.notifyDataSetChanged();
}
#Override
protected void onPostExecute(Integer i) {
}
}
}
I try to replace the credential with the OAuth:
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true);
cb.setOAuthConsumerKey("*************");
cb.setOAuthConsumerSecret("*************");
cb.setOAuthAccessToken("*************");
cb.setOAuthAccessTokenSecret("*************");
Didn't work..(I have all the correct keys and secrets)
I also tried to insert this whole part into one currently operational twitter client(I can get all the tweets on timeline and all), I don't know if I did it right but it didn't work either. Also in this case, if the Oauth was done again in this code and it worked, does that mean when I run the application I have to be redirected to the authorization page twice if I wanted to use this filter function? I would love a fix that the twitter feed can be used by both the timeline and this filtering mode.
Would anybody shed some lights on how I can do this?
Problem solved.
Here is the modified code:
protected Integer doInBackground(Integer... params) {
try {
DefaultHttpClient client = new DefaultHttpClient();
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY,
CONSUMER_SECRET);
consumer.setTokenWithSecret(ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
HttpGet request = new HttpGet();
request.setURI(new URI("https://stream.twitter.com/1/statuses/filter.json?track=" + mSearchTerm));
consumer.sign(request);
HttpResponse response = client.execute(request);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader( new InputStreamReader(in) );
parseTweets(reader);
in.close();
}
So I have below Android code that works. But only until the point pointed out below in the code. The HTTPPost Gets back a JSON string from a webserver. In the postExecute I check the returned JSONObject on the key value "success". If it is 1 then do something. Else do something else. However the "do something else" is not working. Not sure why not. App does not crash but simply goes back to the screen.
Also any tips for better code on below is also appreciated as I am new to this.
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Registreren extends ActionBarActivity {
EditText inputName;
EditText inputEmail;
EditText inputPass;
TextView textError;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registreren);
// Importing all assets like buttons, text fields
inputName = (EditText) findViewById(R.id.register_name);
inputEmail = (EditText) findViewById(R.id.register_email);
inputPass = (EditText) findViewById(R.id.register_pass);
textError = (TextView) findViewById(R.id.register_error);
}
public void registreer (View v) {
String serverURL = "http://www.somesite.com";
new LongOperation().execute(serverURL);
}
public void openLogin (View view) {
Intent intent = new Intent(this, Login.class);
startActivity(intent);
}
private class LongOperation extends AsyncTask<String, Void, JSONObject> {
private ProgressDialog Dialog = new ProgressDialog(Registreren.this);
protected void onPreExecute() {
Dialog.setMessage("Een moment geduld aub...");
Dialog.show();
}
protected JSONObject doInBackground(String... urls) {
String naam = inputName.getText().toString();
String email = inputEmail.getText().toString();
String pass = inputPass.getText().toString();
JSONObject finalResult = null;
HttpParams httpParameters = new BasicHttpParams();
//Set the connection timeout and socket timeout parameters (ms)
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters,5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost("http://www.somesite.com");
try {
List<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("username", naam));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("pass", pass));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity =response.getEntity();
if (responseEntity != null){
BufferedReader reader = new BufferedReader(
new InputStreamReader(responseEntity.getContent(),"UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line ; (line = reader.readLine()) !=null;) {
builder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(builder.toString());
try{
finalResult = new JSONObject(tokener);
} catch (JSONException e) {Toast.makeText(getApplicationContext(), "Data error.Probeer het later nog eens", Toast.LENGTH_LONG).show(); }
} else {
Toast.makeText(getApplicationContext(), "Geen response", Toast.LENGTH_LONG).show();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return finalResult;
}
protected void onPostExecute(JSONObject result) {
Integer succes;
String naam;
String pass;
String email;
try {
succes = result.getInt("succes");
naam = result.getString("username");
pass = result.getString("pass");
email = result.getString("email");
if(succes==1){
SharedPreferences userDetails =getSharedPreferences("userdetails", MODE_PRIVATE);
SharedPreferences.Editor edit = userDetails.edit();
edit.clear();
edit.putString("username", naam);
edit.putString("password", pass);
edit.apply();
Intent intent = new Intent (getApplicationContext(),Overzicht.class);
startActivity(intent);
}
else {//in debug i can come until this line
if(naam.equals("user_bestaat")){//this line and below is ignored
TextView t = (TextView)findViewById(R.id.register_error);
t.setText("Gebruikersnaam bestaat al");
}
if(email == "email_bestaat"){
TextView t = (TextView)findViewById(R.id.register_error);
t.setText("Email is al geregistreerd");
}
}
} catch (JSONException e){Toast.makeText(getApplicationContext(), "Data error.Probeer het later nog eens", Toast.LENGTH_LONG).show(); }
Dialog.dismiss();
//SharedPreferences userDetails = getSharedPreferences("userdetails", MODE_PRIVATE);
// System.out.println("value of the userdertails ==========>"+ userDetails);
//String Uname="";
//String pass= "";
// Uname = userDetails.getString("username", "");
//pass = userDetails.getString("password", "");
}
}
#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_overzicht, 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);
}
}
Comparing with == means compare by reference which is not the case here. You want to compare the value of two strings.
Change to this
if(email.equals("email_bestaat")){
TextView t = (TextView)findViewById(R.id.register_error);
t.setText("Email is al geregistreerd");
}
I am trying to make an app where i am supposed to send data from the application to a web server.
So far i've been searching and not been able to find a working example, i've found some using asynctask which does not work, so any help is appreciated!
try below code :-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.hmkcode.android.vo.Person;
public class MainActivity extends Activity implements OnClickListener {
TextView tvIsConnected;
EditText etName,etCountry,etTwitter;
Button btnPost;
Person person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the views
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
etName = (EditText) findViewById(R.id.etName);
etCountry = (EditText) findViewById(R.id.etCountry);
etTwitter = (EditText) findViewById(R.id.etTwitter);
btnPost = (Button) findViewById(R.id.btnPost);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
}
else{
tvIsConnected.setText("You are NOT conncted");
}
// add click listener to Button "POST"
btnPost.setOnClickListener(this);
}
public static String POST(String url, Person person){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name", person.getName());
jsonObject.accumulate("country", person.getCountry());
jsonObject.accumulate("twitter", person.getTwitter());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.btnPost:
if(!validate())
Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");
break;
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
person = new Person();
person.setName(etName.getText().toString());
person.setCountry(etCountry.getText().toString());
person.setTwitter(etTwitter.getText().toString());
return POST(urls[0],person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
}
private boolean validate(){
if(etName.getText().toString().trim().equals(""))
return false;
else if(etCountry.getText().toString().trim().equals(""))
return false;
else if(etTwitter.getText().toString().trim().equals(""))
return false;
else
return true;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
see below link for more info :-
http://hmkcode.com/android-send-json-data-to-server/
http://androidexample.com/How_To_Make_HTTP_POST_Request_To_Server_-_Android_Example/index.php?view=article_discription&aid=64&aaid=89
Try this,
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class AdminLogin extends Activity {
EditText adminUN, adminPass;
CheckBox cb;
Button loginBtn;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
// Your IP address or your website complete address
String adminLoginURL = "http://192.168.1.1/admin_login.php";
ProgressDialog dialog = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.admin_login);
loginBtn = (Button) findViewById(R.id.adminLogin);
adminUN = (EditText) findViewById(R.id.adminUName);
adminPass = (EditText) findViewById(R.id.adminPass);
loginBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new Admin_Login().execute();
}
});
}
class Admin_Login extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(AdminLogin.this);
dialog.setMessage("Please Wait..!");
dialog.setIndeterminate(false);
dialog.setCancelable(true);
dialog.show();
}
protected String doInBackground(String... params) {
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
dialog.dismiss();
}
}
void login() {
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost(adminLoginURL);
// add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", adminUN
.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password", adminPass
.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost,
responseHandler);
boolean matches = response.startsWith("User Found");
if (matches) {
// Do something start an Activity or do anything you wanted
}
} else {
showAlert();
}
} catch (Exception e) {
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert() {
AdminLogin.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(
AdminLogin.this);
builder.setTitle("Login Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_exit, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_exit:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Create an .xml file to get the username, password, and login button
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/ic_wall"
android:gravity="center_horizontal"
android:orientation="vertical" >
<EditText
android:id="#+id/adminUName"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginTop="50dip"
android:hint="Username"
android:singleLine="true" />
<requestFocus />
<EditText
android:id="#+id/adminPass"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:ems="10"
android:hint="Password"
android:inputType="textPassword"
android:singleLine="true" />
<Button
android:id="#+id/adminLogin"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dip"
android:text="Login"
android:textColor="#0b84aa" />
</LinearLayout>
You must have PhpMyAdmin to try this in local system, if you have hosted server part then try use the following php code and run it.
adminLogin.php
<?php
$hostname_localhost ="";
$database_localhost ="";
$username_localhost ="";
$password_localhost ="";
# Make sure above fields are filled with your config values (must)
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
if (empty($_POST['username'])) {
echo "Please Enter a name";
} else {
$username = $_POST['username'];
}
if (empty($_POST['password'])) {
echo "Please Enter Your Password ";
} else {
$password = SHA1($_POST['password']);
}
$query_search = "select * from adminregister where username = '".$username."' AND password = '".$password."'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) {
echo "\nNo Such User Found";
}
else {
echo "User Found";
}
mysql_close();
?>
Note: You need to create database and table specified in mysql to feed and retrieve the data
If any errors please leave a comment.
So I am trying to create an Android app which basically reads out the twitter feed according to the search query inside a UI. The feed that I need to display form the parsed JSON is the user name, handle, profile picture and the tweet.
Now I have created the whole thing and my code compiles but as soon as I run it the app opens and I write something in the search feed and hit enter - " Unfortunately, AppName has stopped working " I am attaching my logcat and my source code for reference.
*Solved the issue by removing set text from DoInBackground and then giving adequate permission for Android to access internet. The issue now is that as I try and display the profile picture, the URL gets displayed, not the image.
Source code :
package com.example.twittersearchactivity;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class TwitterSearchActivity extends Activity {
private TextView tweetDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twitter_search);
tweetDisplay = (TextView)findViewById(R.id.tweet_txt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.twitter_search, menu);
return true;
}
public void searchTwitter(View view){
EditText searchTxt = (EditText)findViewById(R.id.search_edit);
String searchTerm = searchTxt.getText().toString();
if(searchTerm.length()>0){
try{
String encodedSearch = URLEncoder.encode(searchTerm, "UTF-8");
String searchURL = "http://search.twitter.com/search.json?q="+encodedSearch;
new GetTweets().execute(searchURL);
Log.i("1", "entered the searchterm");
}
catch(Exception e){
tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();
}
}
else
tweetDisplay.setText("Enter a search query!");
}
private class GetTweets extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... twitterURL) {
StringBuilder tweetFeedBuilder = new StringBuilder();
for (String searchURL : twitterURL) {
HttpClient tweetClient = new DefaultHttpClient();
try {
HttpGet tweetGet = new HttpGet(searchURL);
HttpResponse tweetResponse = tweetClient.execute(tweetGet);
StatusLine searchStatus = tweetResponse.getStatusLine();
if (searchStatus.getStatusCode() == 200) {
HttpEntity tweetEntity = tweetResponse.getEntity();
Log.i("2", "entered gettweets");
InputStream tweetContent = tweetEntity.getContent();
InputStreamReader tweetInput = new InputStreamReader(tweetContent);
BufferedReader tweetReader = new BufferedReader(tweetInput);
String lineIn;
while ((lineIn = tweetReader.readLine()) != null) {
tweetFeedBuilder.append(lineIn);
Log.i("3", "entered while in dobackground");
}
}
else {Log.i("error", "error");}
//tweetDisplay.setText("Whoops - something went wrong!");
}
catch(Exception e) {
Log.e("DEBUGTAG", "Remote Image Exception", e);
//tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();
}}
return tweetFeedBuilder.toString();
}
protected void onPostExecute(String result) {
StringBuilder y;
StringBuilder tweetResultBuilder = new StringBuilder();
try {
Log.i("tag", "entered try block");
JSONObject resultObject = new JSONObject(result);
JSONArray tweetArray = resultObject.getJSONArray("results");
for (int t=0; t<tweetArray.length(); t++) {
Log.i("tag", "entered the json stream");
JSONObject tweetObject = tweetArray.getJSONObject(t);
tweetResultBuilder.append(tweetObject.getString("from_user")+": ");
tweetResultBuilder.append(tweetObject.getString("from_user_name")+": ");
tweetResultBuilder.append(tweetObject.get("text")+"\n\n");
String imageURL = (String) tweetObject.get(("profile_image_url")+": ");
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
#SuppressWarnings("deprecation")
Drawable d =new BitmapDrawable(bitmap);
d.setAlpha(255);
TextView.setCompoundDrawablesWithIntrinsicBounds(0,0,1,0);
}
}
catch (Exception e) {
tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();}
if(tweetResultBuilder.length()>0)
tweetDisplay.setText(tweetResultBuilder.toString());
else
tweetDisplay.setText("Sorry - no tweets found for your search!");
}
}}
You can't call view functions like setText on another thread like an AsyncTask doInBackground function. You need to do it in onPostExecute.
I just build a demo application through async task and now i want the json data in list view so i dont know where i can add json functions and array list etc so plz guide me or help me by edit the code i thankful in advance and plz help im new to android and java
package your.packag.namespace;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class runActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://192.168.1.156/recess/document/document");
HttpClient client = new DefaultHttpClient();
HttpResponse response=null;
try{
response = client.execute(httpGet);}
catch(Exception e){}
System.out.println(response.getStatusLine());
String text = null;
try {
response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
EditText et = (EditText)findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}}
You can use the built-in org.json classes to convert the retrieved string (your text variable content) in to JSON objects.
Have a look at the tutorial from Lars Vogel on how to do that.