Search the Blog

Thursday, August 15, 2019

Json Parser Code for Android to JAVA MVC Project Uploading The Image

This Blog post have the complete Code for an Android Application which have database at cload and running on apache TOMCAT.


Json Parser Code for Android to JAVA MVC Project Uploading The Image

In this blog post you can get all information easily which is required to send a request from android application to server(cloud)  and receive and extract  the data in usable format.


This Code is used in School ERP Application for uploading The Image of Code



package com.example.sawan.onlineattendance; // Package Name of Project
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * Created by sawan on 9/28/2016.
 */

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
static InputStream iStream = null;
static JSONArray jarray = null;

public JSONParser() {}
public JSONObject makeHttpRequest(String url2, String method, List < NameValuePair > params)\ {
try {
if (method == "POST") {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
else {
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}

}
catch(UnsupportedEncodingException e) {
System.out.println("UnsupportedEncodingException");
e.printStackTrace();
}
catch(ClientProtocolException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch(Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
jObj = new JSONObject(json);
}
catch(JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;

}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
else {
Log.e("==>", "Failed to download file");
}
} catch(ClientProtocolException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
try {
jarray = new JSONArray(builder.toString());
} catch(JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jarray;
}

public JSONObject makeHttpRequest2(String url) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch(UnsupportedEncodingException e) {
e.printStackTrace();
} catch(ClientProtocolException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch(Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

try {
jObj = new JSONObject(json);
} catch(JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;

}
}


100+ JAVA Pattern Program






50+ Python Pattern Program



See Also-



Android Code for opening Multiple Screen from a single Activity

This Blog post have the complete Code for an Android Application about various activity opening from ia single screen 

Android Code for opening Multiple Screen from a single Activity



In this blog post you can get all information relatated activating new activity from previous activity with actual runnable code.


This code is part of Android application MVC Project of School ERP. If you are faminliar with java and also have some good hands on Anadroid then you can easilly understand the code and can use this code in your own project.


package com.example.sawan.onlineattendance;

import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;

public class HOD extends AppCompatActivity {
Button studentremark,
btn2,
notice,
drictorNotice,
hodNotice,
Defaulter,
Inforamtion,
teacherLogin,
teacherremak;
JSONParser jParser = new JSONParser();
JSONObject json;
String buttton;
static String button;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hod);
btn2 = (Button) findViewById(R.id.sdudent_lecture);
btn2.setOnClickListener(new View.OnClickListener() {@Override
public void onClick(View view) {
Intent intent = new Intent(HOD.this, Student_subject_setting.class);
startActivity(intent);
}
});
studentremark = (Button) findViewById(R.id.studentNotification);
studentremark.setOnClickListener(new View.OnClickListener() {@Override
public void onClick(View view) {
Intent intent = new Intent(HOD.this, HODStudentRemark.class);
startActivity(intent);
}
});
teacherremak = (Button) findViewById(R.id.HomeWork);
teacherremak.setOnClickListener(new View.OnClickListener() {@Override
public void onClick(View view) {
Intent intent = new Intent(HOD.this, HomeWork.class);
startActivity(intent);
}
});
teacherLogin = (Button) findViewById(R.id.TeacherLogin);
teacherLogin.setOnClickListener(new View.OnClickListener() {@Override
public void onClick(View view) {
Intent intent = new Intent(HOD.this, HODTeacherLogin.class);
startActivity(intent);
}
});
notice = (Button) findViewById(R.id.update);
notice.setOnClickListener(new View.OnClickListener() {@Override
public void onClick(View view) {
Intent intent = new Intent(HOD.this, HODStudentNotification.class);
startActivity(intent);
}
});
hodNotice = (Button) findViewById(R.id.TecherNotification);

hodNotice.setOnClickListener(new View.OnClickListener() {@Override
public void onClick(View view) {
Intent intent = new Intent(HOD.this, HODStaffNotice.class);
startActivity(intent);
}
});
Defaulter = (Button) findViewById(R.id.DefaulterStudent);
Defaulter.setOnClickListener(new View.OnClickListener() {@Override
public void onClick(View view) {
Intent intent = new Intent(HOD.this, DefaulterCutOf.class);
startActivity(intent);
}
});
Inforamtion = (Button) findViewById(R.id.StudentDetail);
Inforamtion.setOnClickListener(new View.OnClickListener() {@Override
public void onClick(View view) {
Intent intent = new Intent(HOD.this, DirectorStudentFinal.class);
startActivity(intent);
}
});
drictorNotice = (Button) findViewById(R.id.DirectorNotice);
drictorNotice.setOnClickListener(new View.OnClickListener() {@Override
public void onClick(View view) {
new Login().execute();
}

});

}
private class Login extends AsyncTask < String,
String,
String > {@SuppressWarnings("WrongThread")@Override
protected String doInBackground(String...strings) {
String table = Identification.TableName; {
String url_login2 = "http://192.168.43. 156:8081/OnlineAttendance/DirectorNoticeServlet";
List < NameValuePair > params_dizsweb = new ArrayList < NameValuePair > ();
params_dizsweb .add(new BasicNameValuePair("t", Identification.TableName));
params_dizsweb .add(new BasicNameValuePair("cutoff", "HODDrictor"));
params_dizsweb .add(new BasicNameValuePair("text", "faltu"));
json = jParser.makeHttpRequest(url_login2, "GET", params);
String s = null;
try {
if (json.getString("info").equals("success")) {
Identification.FacultyDrictorNotices = json.getString("name");
Intent login = new Intent(getApplicationContext(), HODDrictorNotice.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
}
else {
Intent login = new Intent(getApplicationContext(), Error.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
}
} catch(Exception e) {
e.printStackTrace();
}
}
return null;
}
}
}


Star Pattern Program JAVA

Android java code settiong of subject in MVC

package com.example.sawan.onlineattendance;



Android java code settiong of subject in MVC


import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class FacultySubjectSetting extends AppCompatActivity {
 Button btn;
    String fca;
    JSONParser jParser = new JSONParser();
    JSONObject json;
    private static String url_login = "http://  192. 168. 43. 156: 8081 /OnlineAttendance/UpdateTeaherSubjectSettingSearch";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_faculty_subject_setting);
        btn=(Button)findViewById(R.id.search);
        Spinner spinner4 = (Spinner) findViewById(R.id.spinner_faculty);
        ArrayAdapter<CharSequence> adapter4 = ArrayAdapter.createFromResource(
                this, R.array.Faculty, android.R.layout.simple_spinner_item);
        adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner4.setAdapter(adapter4);
        spinner4.setOnItemSelectedListener(new MyOnItemSelectedListener());

 btn.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {
         Spinner sp4 = (Spinner)findViewById(R.id.spinner_faculty);
         String   facu = sp4.getSelectedItem().toString();
         fca=Integer.parseInt(facu)+"";
         new Login().execute();
     }
 });
    }
    private class Login extends AsyncTask<String, String, String> {
        @SuppressWarnings("WrongThread")
        @Override
        protected String doInBackground(String... strings) {
            String username = fca;
            String table = Identification.TableName;
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("u",username));
            params.add(new BasicNameValuePair("t",table));
            json = jParser.makeHttpRequest(url_login, "GET", params);
            String Sname=null;

            try {
                System.out.println(json.getString("info"));
                int m=json.getInt("row");
                if( json.getString("info").equals("success"))
                {
                    int j=1;
                    Identification.FacultySubjectRecord=new String[m][3];
                    Identification.FacultyCode=json.getString("facultyCode");
                    System.out.println("condition is : "+(j<=m));
                    while(j<=m)
                    {
                        String sub=json.getString("sub"+j);
                        System.out.println("inseide "+sub);
                        System.out.println("inseide "+Identification.FacultySubjectRecord.length);
                        System.out.println("inseide "+(j-1));
                        System.out.println("inseide "+Identification.FacultySubjectRecord[j-1][0]);
                        Identification.FacultySubjectRecord[j-1][0]=sub;
                        System.out.println("nrfjnkmlk kgkm :");
                        System.out.println("inseide              "+Identification.FacultySubjectRecord[j-1][0]);
                        String branch=json.getString("branch"+j);

                        Identification.FacultySubjectRecord[j-1][1]=branch;

                        String section=json.getString("section"+j);

                        Identification.FacultySubjectRecord[j-1][2]=section;
                        System.out.println("inseide              "+Identification.FacultySubjectRecord[j-1][2]);

                        System.out.println("j value is : "+j);
                      j++;
                    }
                    Intent login = new Intent(getApplicationContext(),FacultySubjectSettingPage.class);
                    System.out.println("........................................ login.....................................................");
                    login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    System.out.println("........................................ 1......................................................");
                    startActivity(login);
                    finish();
                }
                else
                {
                    Intent login = new Intent(getApplicationContext(), Error.class);
                    System.out.println("........................................ login.....................................................");
                    login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    System.out.println("........................................ 1......................................................");
                    startActivity(login);
                    finish();
                }

            }
            catch (Exception e)
            {


            }
            return null;
        }
    }


}

Translate