hi,
this is a single Item View of a ListView. I wan't to go to email
client when clicking a Button in below fragment. there is a email
column in parse database . when clicking the button it should lead to
email client with that particular email id of this single item view .
I tried some code its not working anyone please help ??
import android.content.*;
import android.graphics.*;
import android.net.*;
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.*;
import android.view.View;
import android.widget.*;
import com.parse.*;
import com.parse.ParseException;
import com.squareup.picasso.*;
import java.io.*;
import java.net.*;
public class SingleItemView extends AppCompatActivity {
String objectId;
protected TextView txtv;
protected TextView txtv1;
protected ImageView txtv2;
protected ImageView txtv3;
Button sendEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_item_view);
txtv =(TextView)findViewById(R.id.txt123);
txtv1 =(TextView)findViewById(R.id.txt1234);
txtv2 =(ImageView)findViewById(R.id.txt12345);
txtv3 =(ImageView)findViewById(R.id.txt123456);
Intent i =getIntent();
objectId = i.getStringExtra("objectId");
ParseQuery<ParseObject> query = ParseQuery.getQuery("_User");
query.getInBackground(objectId, new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
String username = object.getString("firstname");
txtv.setText(username);
String position = object.getString("position");
txtv1.setText(position);
URL url = null;
try {
url = new URL("http://izi-dev.fr/fbc/assets/uploads/" + object.getString("image"));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
txtv2.setImageBitmap(bmp);
URL url1 = null;
try {
url = new URL("http://izi-dev.fr/fbc/assets/uploads/" + object.getString("image"));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
Bitmap bmp1 = null;
try {
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
txtv3.setImageBitmap(bmp);
} else {
// something went wrong
}
}
});
sendEmail = (Button) findViewById(R.id.button5);
sendEmail.setOnClickListener((View.OnClickListener) this);
}
public void onClick(View v) {
try{
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL , "email");
emailIntent.setType("text/plain"); // <-- HERE
startActivity(emailIntent); // <-- AND HERE
}finally {
}
}
}
Try this:
sendEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(view.getId()==R.id.button5){
Intent i = new Intent(Intent.ACTION_SEND);
i.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ emailAddress });
i.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
i.putExtra(android.content.Intent.EXTRA_TEXT, text);
startActivity(Intent.createChooser(i, "Send email"));
}
}
});
You have set the click listener in wrong way.
Implement the ClickListener
public class SingleItemView extends AppCompatActivity implements View.OnClickListener
Set the listener
sendEmail.setOnClickListener(this);
Use annotations
#Override
public void onClick(View v)
Please try that.
As i may understood correctly your problem, I suggest you to use the following plugin https://github.com/katzer/cordova-plugin-email-composer#examples. Basically with this plugin you can send HTML embodeed body with the click of a button.
cordova.plugins.email.open({
to: 'max#mustermann.de',
subject: 'Greetings',
body: '<h1>Nice greetings from Leipzig</h1>',
isHtml: true
});
Please check the documentation for further info. I hope i helped you.
Related
The problem as seen in the title appears in line 102 of the code down below. Im very new to this topic and Im trying to make an app which can control an arduino... This part of code I show you is supposed to manage the connection to the Bluetooth Module and in my MainActivity I plan to send the letters to the other device.
I hope someone can help.
My code (BT_Classic.java):
package com.car.bluetooth.bluetoothcar;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class BT_Classic extends AppCompatActivity {
private Button pairedButton;
private Button discoveredButton;
private Button btonButton;
private Button btoffButton;
private ProgressDialog progress;
ListView listView;
BluetoothSocket bluetoothSocket;
BluetoothDevice bluetoothDevice;
private final static UUID uuid = UUID.fromString("fc5ffc49-00e3-4c8b-9cf1-6b72aad1001a");
private ArrayList<String> mDeviceList = new ArrayList<String>();
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
//BLUETOOTH VERBINDUNG
private static final int REQUEST_ENABLED = 0;
private static final int REQUEST_DISCOVERABLE = 0;
private class ConnectingThread extends Thread {
public ConnectingThread(BluetoothDevice device) {
BluetoothSocket temp = null;
BluetoothDevice bluetoothDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
temp = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
bluetoothSocket = temp;
}
public void run() {
// Cancel any discovery as it will slow down the connection
btAdapter.cancelDiscovery();
try {
// This will block until it succeeds in connecting to the device
// through the bluetoothSocket or throws an exception
bluetoothSocket.connect();
} catch (IOException connectException) {
connectException.printStackTrace();
try {
bluetoothSocket.close();
} catch (IOException closeException) {
closeException.printStackTrace();
}
}
// Code to manage the connection in a separate thread
/*
manageBluetoothConnection(bluetoothSocket);
*/
}
// Cancel an open connection and terminate the thread
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bt__classic);
pairedButton = (Button) findViewById(R.id.pairedButton);
discoveredButton = (Button) findViewById(R.id.discoveredButton);
btonButton = (Button) findViewById(R.id.btonButton);
btoffButton = (Button) findViewById(R.id.btoffButton);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemValue = (String) listView.getItemAtPosition(position);
String MAC = itemValue.substring(itemValue.length() - 17);
BluetoothDevice bluetoothDevice = btAdapter.getRemoteDevice(MAC);
// Initiate a connection request in a separate thread
ConnectingThread t = new ConnectingThread(bluetoothDevice);
t.start();
}
});
//Pairing Button
pairedButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
ArrayList<String> devices = new ArrayList<String>();
for (BluetoothDevice bt : pairedDevices){
devices.add(bt.getName());
devices.add(bt.getAddress());
}
ArrayAdapter arrayAdapter = new ArrayAdapter(BT_Classic.this, android.R.layout.simple_list_item_1, devices);
listView.setAdapter(arrayAdapter);
}
});
discoveredButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!btAdapter.isDiscovering()){
Intent bton = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(bton, REQUEST_DISCOVERABLE);
}
}
});
btonButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent bton = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(bton, REQUEST_ENABLED);
}
});
btoffButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btAdapter.disable();
}
});
}
}
You have an extra } in this section
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
} // Close try
} // Close cancel()
} // Close ConnectingThread
} // DELETE THIS CURLY BRACE
First, it was problem with extra curly braces as Chris has mentioned.
Second, you haven't define your ListView as listView = findViewById(R.id.your_id);
That's it, and good luck. :)
I have a ListView created . and when I click a single item of the ListView, I'm calling an activity to show the single item View. TextView data is parsing. but when I'm trying to call an image from parse its not loading (the image is hosted in a separate location online). if any one can please tell how to load image here ??
my file url
url = new URL("file location " + statusObject.getString("image"));
edited code
URL url = null;
try {
url = new URL("https://www.gravatar.com/avatar/db5bfe41c9d21d3a5b4e5b5f6a2d776d?s=32&d=identicon&r=PG&f=1");
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
txtv2.setImageBitmap(bmp);
////////////////
single item view
import android.content.*;
import android.net.*;
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.*;
import android.view.View;
import android.widget.*;
import com.parse.*;
import com.parse.ParseException;
public class SingleItemView extends AppCompatActivity {
String objectId;
protected TextView txtv;
protected TextView txtv1;
protected ImageView txtv2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_item_view);
txtv =(TextView)findViewById(R.id.txt123);
txtv1 =(TextView)findViewById(R.id.txt1234);
txtv2 =(ImageView)findViewById(R.id.txt12345);
Intent i =getIntent();
objectId = i.getStringExtra("objectId");
ParseQuery<ParseObject> query = ParseQuery.getQuery("_User");
query.getInBackground(objectId, new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
String username = object.getString("firstname");
txtv.setText(username);
String position = object.getString("position");
txtv1.setText(position);
String img_ = object.getString("image");
txtv2.setImageURI(Uri.parse(img_));
} else {
// something went wrong
}
}
});
}
}
fragment file
import android.content.*;
import android.os.Bundle;
import android.support.v4.app.*;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import java.util.ArrayList;
import java.util.List;
public class Individuals extends android.support.v4.app.ListFragment
implements FindCallback<ParseObject> {
private List<ParseObject> mOrganization = new ArrayList<ParseObject>();
SearchView sv;
IndividualsAdaptor adaptor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.individuals, container, false);
}
#Override
public void onViewCreated(View view, Bundle b) {
super.onViewCreated(view, b);
sv = (SearchView) view.findViewById(R.id.ser1);
adaptor = new IndividualsAdaptor(getActivity(), mOrganization);
setListAdapter(adaptor);
ParseQuery.getQuery("_User").findInBackground(this);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adaptor.getFilter().filter(text);
return true;
}
});
}
#Override
public void done(List<ParseObject> scoreList, ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + scoreList.size() + " _User");
mOrganization.clear();
mOrganization.addAll(scoreList);
((IndividualsAdaptor) getListAdapter()).updateBackupList(mOrganization);
((IndividualsAdaptor) getListAdapter()).notifyDataSetChanged();
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
#Override
public void onListItemClick(android.widget.ListView l, android.view.View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ParseObject prs = mOrganization.get(position);
String objectId = prs.getObjectId();
Intent i = new Intent(getActivity(), SingleItemView.class);
i.putExtra("objectId", objectId);
startActivity(i);
}
}
Define <uses-permission android:name="android.permission.INTERNET" /> in Manifest.xml.
Then use Picasso or Gilde and parse images from their respective instances and pass image URL that you are querying from parsing. These libraries will parse URL and return image in the ImageView.
Other similar questions:
Load image from url
How to load an ImageView by URL in Android?
finally this code is working after editing some codes form the link in the answer . by this code you can
call images dynamically for each of the Object id.
URL url = null;
try {
url = new URL("image url" + object.getString("image"));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
txtv2.setImageBitmap(bmp);
// something went wrong
First of all, I should say that I am a newbie on Java and Android programming. I am very experienced in C programming for embedded systems, but now I need to communicate one of my embedded projects with an Android app, in a very simple way. I am using one of those ESP8266, configured as default. Thus, it behaves as a basic telnet server. My microcontroller has to send a question (through a string, which is not constant) to my app, and receive a "Y" or "N" reply. I have tested it using a telnet client, and it is working fine. However, I want to have an app that pops up an alert dialog and/or show the message in a TextView element, and sends the reply after some button click. For this, I have adapted a telnet client code from:
http://android-er.blogspot.com.br/2014/08/simple-android-chat-application-client.html
I have put everything in one single panel, and reduced the number of elements to a textview element and 4 buttons (connect, disconnect, yes, and no). I am using a fixed IP and port to connect the app to my laptop, which is running a telnet server (hercules). The connection is confirmed, and the YES and NO buttons are sending the correct messages. However, the question string never shows up at the TextView element. I have also added an AlertDialog to pop up, because I think it is more appropriate to the kind of app I am developing.
Notice that the testing of the message income happens inside a thread, and I am calling the TextView update and the AlertDialog show using runOnUiThread.
Here is the Java code (not optimized yet):
package br.unicamp.smpci;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
static final int SocketServerPORT = 80;
final Context context = this;
LinearLayout Panel;
Button buttonConnect;
TextView chatMsg;
Button buttonSendYes;
Button buttonSendNo;
Button buttonDisconnect;
String msgLog = "";
ChatClientThread chatClientThread = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Panel = (LinearLayout)findViewById(R.id.panel);
buttonConnect = (Button) findViewById(R.id.connect);
buttonDisconnect = (Button) findViewById(R.id.disconnect);
chatMsg = (TextView) findViewById(R.id.chatmsg);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
buttonDisconnect.setOnClickListener(buttonDisconnectOnClickListener);
buttonSendYes = (Button)findViewById(R.id.sendYes);
buttonSendYes.setOnClickListener(buttonSendYesOnClickListener);
buttonSendNo = (Button)findViewById(R.id.sendNo);
buttonSendNo.setOnClickListener(buttonSendNoOnClickListener);
}
OnClickListener buttonDisconnectOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(chatClientThread==null){
return;
}
chatClientThread.disconnect();
}
};
OnClickListener buttonSendYesOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(chatClientThread==null){
return;
}
chatClientThread.sendMsg("Y" + "\n");
}
};
OnClickListener buttonSendNoOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(chatClientThread==null){
return;
}
chatClientThread.sendMsg("N" + "\n");
}
};
OnClickListener buttonConnectOnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
String textAddress = "192.168.1.11";
msgLog = "NO MESSAGES";
chatMsg.setText(msgLog);
chatClientThread = new ChatClientThread(
textAddress, SocketServerPORT);
chatClientThread.start();
}
};
private class ChatClientThread extends Thread {
String dstAddress;
int dstPort;
String msgToSend = "";
boolean goOut = false;
ChatClientThread(String address, int port) {
dstAddress = address;
dstPort = port;
}
#Override
public void run() {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket(dstAddress, dstPort);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
while (!goOut) {
if (dataInputStream.available() > 0) {
msgLog = dataInputStream.readUTF();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
chatMsg.setText(msgLog);
chatMsg.invalidate();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setTitle("ALERT");
alertDialogBuilder
.setMessage(MsgLog)
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
if(chatClientThread==null){
return;
}
chatClientThread.sendMsg("Y" + "\n");
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (chatClientThread == null) {
return;
}
chatClientThread.sendMsg("N" + "\n");
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
}
if(!msgToSend.equals("")){
dataOutputStream.writeUTF(msgToSend);
dataOutputStream.flush();
msgToSend = "";
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
final String eString = e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, eString, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
final String eString = e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, eString, Toast.LENGTH_LONG).show();
}
});
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
//loginPanel.setVisibility(View.VISIBLE);
//chatPanel.setVisibility(View.GONE);
}
});
}
}
private void sendMsg(String msg){
msgToSend = msg;
}
private void disconnect(){
goOut = true;
}
}
}
I have done extensive research on how to make sure that the UI thread updates my elements, and I am using the Show() method for the alertdialog, and invalidating the TextView element to force it to update. I have used debug, and I am sure that the instructions are being executed, but with no result on my app ( I am using a real device for debugging).
I have seen that maybe I could use AsyncTask for this purpose, but as a newbie I am facing difficulties to make the changes, and I believe that calling the updates with a runOnUiThread should do the work.
Can anyone explain why I cannot see my message, and maybe provide me a code correction?
Thanks in advance,
Antonio Quevedo
Here is my java code for loading a title, description, date and an image from Mysql through Php in a loop. Everything loading perfectly except image. When I load image the loading dialog box displaying and I can see only one image in the background but the loading dialogue box is still appearing. I'm new in android so I need experts help like you.
JAVA
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Dialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class News_events extends Fragment {
private String jsonResult;
private String url = "http://192.168.2.7/crescentnews/select.php";
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
ImageView img;
Bitmap bitmap;
ProgressDialog pDialog;
InputStream is=null;
String result=null;
String line=null;
int code;
public News_events(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_news_events, container, false);
accessWebService();
return rootView;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
display();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void display() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news_details");
LinearLayout MainLL= (LinearLayout)getActivity().findViewById(R.id.newslayout);
//LinearLayout headLN=(LinearLayout)findViewById(R.id.headsection);
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
final String head = jsonChildNode.optString("title");
final String details = jsonChildNode.optString("text");
final String date = jsonChildNode.optString("date");
final String image = jsonChildNode.optString("img");
//final String time = jsonChildNode.optString("time");
//img = new ImageView(this.getActivity());
//new LoadImage().execute("http://192.168.2.7/crescentnews/images/"+image);
img = new ImageView(this.getActivity());
LoadImage ldimg=new LoadImage();
ldimg.setImage(img);
ldimg.execute("http://192.168.2.7/crescentnews/images/"+image);
TextView headln = new TextView(this.getActivity());
headln.setText(head); // News Headlines
headln.setTextSize(20);
headln.setTextColor(Color.BLACK);
headln.setGravity(Gravity.CENTER);
headln.setBackgroundResource(R.drawable.menubg);
headln.setPadding(10, 20, 10, 0);
headln.setWidth(100);
headln.setClickable(true);
headln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(), head, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity().getApplicationContext(),MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
ImageView photo=new ImageView(this.getActivity());
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
photo.setBackgroundColor(Color.parseColor("#000000"));
photo.setPadding(0, 0, 10, 10);
photo.setClickable(true);
// Drawable drawable = LoadImageFromWebOperations("http://192.168.2.7/crescentnews/images/"+pic);
// userpic.setImageDrawable(drawable);
TextView dateln = new TextView(this.getActivity());
dateln.setText(date); // News Headlines
dateln.setTextSize(12);
dateln.setTextColor(Color.BLACK);
dateln.setGravity(Gravity.RIGHT);
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
dateln.setBackgroundColor(0x00000000);
dateln.setPadding(0, 0, 10, 10);
dateln.setWidth(100);
dateln.setClickable(true);
dateln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
View sep=new View(this.getActivity());
sep.setBackgroundColor(Color.parseColor("#252525"));
sep.setMinimumHeight(10);
TextView detailsln = new TextView(this.getActivity());
detailsln.setText(details); // News Details
detailsln.setTextSize(12);
detailsln.setTextColor(Color.BLACK);
detailsln.setGravity(Gravity.LEFT);
detailsln.setPadding(10, 10, 10, 10);
MainLL.addView(headln);
MainLL.addView(dateln);
MainLL.addView(photo);
MainLL.addView(img);
MainLL.addView(detailsln);
MainLL.addView(sep);
detailsln.setClickable(true);
detailsln.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(), MainActivity.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
}
} catch (JSONException e) {
Toast.makeText(getActivity().getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
ImageView img;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Image ....");
pDialog.show();
}
public void setImage(ImageView img ){
this.img=img;
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).openStream());
}
catch (Exception e) { e.printStackTrace(); }
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
pDialog = new ProgressDialog(getActivity());
pDialog.dismiss();
}
pDialog.dismiss();
}
}
your code seems to be ok.
also check some option like volley
Try something like following
private class LoadImage extends AsyncTask<String, String, Bitmap> {
ImageView img;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Image ....");
pDialog.show();
}
public void setImage(ImageView img ){
this.img=img;
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).openStream());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
}
pDialog.dismiss();
}
}
To call this
img = new ImageView(this.getActivity());
LoadImage ldimg=new LoadImage();
ldimg.setImage(img);
ldimg.execute("http://192.168.2.7/crescentnews/images/"+image);
To dismiss dialog show the dialog only once before for loop and dismiss it after for loop
Hope it will help :)
Hey so I am not getting an error, but all my logs get initiated except for the one after HttpResponse not sure why, and on the server end I do not see any activity of a POST coming in...
here is my code:
package com.sfsfdsfds;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
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.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class wardrobe extends Activity{
//set variable for the fields
private EditText nameField;
private Spinner typeField;
private EditText colorField;
private Spinner seasonField;
private EditText sizeField;
private EditText quantityField;
private ImageView imageField;
private ProgressBar progressBarField;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wardrobe);
ImageView user_photo = (ImageView) findViewById(R.id.user_photo);
//button for upload image
Button uploadImageButton = (Button) findViewById(R.id.uploadImageButton);
//button for posting details
Button postWardrobe = (Button) findViewById(R.id.postButton);
//Value of fields
nameField = (EditText) findViewById(R.id.nameFieldWardrobeScreen);
typeField = (Spinner) findViewById(R.id.typeFieldWardrobeScreen);
colorField = (EditText) findViewById(R.id.colorFieldWardrobeScreen);
seasonField = (Spinner) findViewById(R.id.seasonFieldWardrobeScreen);
sizeField = (EditText) findViewById(R.id.sizeFieldWardrobeScreen);
quantityField = (EditText) findViewById(R.id.quantityFieldWardrobeScreen);
imageField = (ImageView) findViewById(R.id.user_photo);
progressBarField = (ProgressBar) findViewById(R.id.progressBarWardrobe);
progressBarField.setVisibility(View.GONE);
//Creating spinner for select/options for type field
Spinner spinnerType = (Spinner) findViewById(R.id.typeFieldWardrobeScreen);
ArrayAdapter<CharSequence> adapterTypeArray = ArrayAdapter.createFromResource(this, R.array.type_array, android.R.layout.simple_spinner_item);
adapterTypeArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerType.setAdapter(adapterTypeArray);
//Creating spinner for select/options for season field
Spinner spinnerSeason = (Spinner) findViewById(R.id.seasonFieldWardrobeScreen);
ArrayAdapter<CharSequence> adapterSeasonArray = ArrayAdapter.createFromResource(this, R.array.season_array, android.R.layout.simple_spinner_item);
adapterSeasonArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSeason.setAdapter(adapterSeasonArray);
uploadImageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//below allows you to open the phones gallery
Image_Picker_Dialog();
}
});
postWardrobe.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//validate input and that something was entered
if(nameField.getText().toString().length()<1 || colorField.getText().toString().length()<1 || sizeField.getText().toString().length()<1 || quantityField.getText().toString().length()<1) {
//missing required info (null was this but lets see)
Toast.makeText(getApplicationContext(), "Please complete all sections!", Toast.LENGTH_LONG).show();
} else {
JSONObject dataWardrobe = new JSONObject();
try {
dataWardrobe.put("type", typeField.getSelectedItem().toString());
dataWardrobe.put("color", colorField.getText().toString());
dataWardrobe.put("season", seasonField.getSelectedItem().toString());
dataWardrobe.put("size", sizeField.getText().toString());
dataWardrobe.put("quantity", quantityField.getText().toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//make progress bar visible
progressBarField.setVisibility(View.VISIBLE);
//execute the post request
new dataSend().postData(dataWardrobe);
}
//below should send data over
}
});
}
// After the selection of image you will retun on the main activity with bitmap image
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Utility.GALLERY_PICTURE)
{
// data contains result
// Do some task
Image_Selecting_Task(data);
} else if (requestCode == Utility.CAMERA_PICTURE)
{
// Do some task
Image_Selecting_Task(data);
}
}
public void Image_Picker_Dialog()
{
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
myAlertDialog.setTitle("Pictures Option");
myAlertDialog.setMessage("Select Picture Mode");
myAlertDialog.setPositiveButton("Gallery", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
Utility.pictureActionIntent = new Intent(Intent.ACTION_GET_CONTENT, null);
Utility.pictureActionIntent.setType("image/*");
Utility.pictureActionIntent.putExtra("return-data", true);
startActivityForResult(Utility.pictureActionIntent, Utility.GALLERY_PICTURE);
}
});
myAlertDialog.setNegativeButton("Camera", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
Utility.pictureActionIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(Utility.pictureActionIntent, Utility.CAMERA_PICTURE);
}
});
myAlertDialog.show();
}
public void Image_Selecting_Task(Intent data)
{
ImageView user_photo = (ImageView) findViewById(R.id.user_photo);
try
{
Utility.uri = data.getData();
if (Utility.uri != null)
{
// User had pick an image.
Cursor cursor = getContentResolver().query(Utility.uri, new String[]
{ android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
// Link to the image
final String imageFilePath = cursor.getString(0);
//Assign string path to File
Utility.Default_DIR = new File(imageFilePath);
// Create new dir MY_IMAGES_DIR if not created and copy image into that dir and store that image path in valid_photo
Utility.Create_MY_IMAGES_DIR();
// Copy your image
Utility.copyFile(Utility.Default_DIR, Utility.MY_IMG_DIR);
// Get new image path and decode it
Bitmap b = Utility.decodeFile(Utility.Paste_Target_Location);
// use new copied path and use anywhere
String valid_photo = Utility.Paste_Target_Location.toString();
b = Bitmap.createScaledBitmap(b, 150, 150, true);
//set your selected image in image view
user_photo.setImageBitmap(b);
cursor.close();
} else
{
Toast toast = Toast.makeText(this, "Sorry!!! You haven't selecet any image.", Toast.LENGTH_LONG);
toast.show();
}
} catch (Exception e)
{
// you get this when you will not select any single image
Log.e("onActivityResult", "" + e);
}
}
#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, menu);
return true;
}
//Calling code for different selected menu options
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
//show settings activity screen (main preference activity file)
case R.id.wardrobe:
Intent intent = new Intent(wardrobe.this, wardrobe.class);
startActivity(intent);
//if index button clicked in menu sub-menu options
case R.id.matches:
Toast.makeText(this, "matches was clicked!", 5).show();
//if index button clicked in menu sub-menu options
case R.id.worn:
Toast.makeText(this, "worn was clicked!", 5).show();
default:
}
return super.onOptionsItemSelected(item);
}
private class dataSend extends AsyncTask<JSONObject, Integer, Double> {
protected Double doInBackground(JSONObject... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result) {
progressBarField.setVisibility(View.GONE);
Toast.makeText(wardrobe.this, "info sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress) {
progressBarField.setProgress(progress[0]);
}
public void postData(JSONObject dataWardrobe) {
Log.v("posting data", "poooooost");
// Create a new HttpClient and Post Header
//int TIMEOUT_MILLISEC = 10000; // = 10 seconds
HttpParams httpParams = new BasicHttpParams();
//HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
//HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient httpclient = new DefaultHttpClient(httpParams);
HttpPost httppost = new HttpPost("http://127.0.0.1:3000/wardrobe");
Log.v("posteed", "posteed url");
try {
Log.v("trying data", "prep");
//add data
StringEntity se = new StringEntity( dataWardrobe.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
Log.v("posteed", "posteed 11");
// execute http post request
HttpResponse response = httpclient.execute(httppost);
Log.v("posteed", "posteed 22");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
}
Not sure what I am doing wrong, I tried various things and trying to look up different ways to go about doing this and none of them have worked... maybe it is something more simple than I see... the problem I think lies in the private class within this class.
I haven't read your code in great detail, but I suspect a strong contributor is this:
HttpPost httppost = new HttpPost("http://127.0.0.1:3000/wardrobe");
If you're using the emulator it's probably more likely you want to connect to "10.0.2.2". which is:
Special alias to your host loopback interface (i.e., 127.0.0.1 on your
development machine)
See here for more details on the emulator networking:
http://developer.android.com/tools/devices/emulator.html#emulatornetworking